Algorithms/- LeetCode
LeetCode - 724. Find Pivot Index [Kotlin]
자굿
2022. 9. 5. 11:00
Find Pivot Index - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
정답 (Solution)
class Solution {
fun pivotIndex(nums: IntArray): Int {
val totalSum = nums.sum()
var leftSum = 0
for(i in 0 until nums.size){
if(leftSum == (totalSum -leftSum - nums[i])){
return i
}
leftSum += nums[i]
}
return -1
}
}
분석
- 전체 합계를 현재 i 번째를 제외한 왼쪽 합계와 같은지 계속 비교하여 같은 경우 해당 i 를 리턴한다
반응형