코린이의 소소한 공부노트

[LeetCode/Easy] 724. Find Pivot Index 본문

코딩테스트 풀이/JAVA

[LeetCode/Easy] 724. Find Pivot Index

무지맘 2022. 12. 6. 19:41

1. Input

1) int 배열 nums

 

2. Output

1) numspivot index를 구해서 반환

2) nums[0] ~ nums[i-1]까지의 합과 nums[i+1] ~ nums[end]까지의 합이 같을 때, ipivot index가 된다.

3) pivot index가 여러개인 경우 가장 왼쪽 인덱스를 반환하고, 없다면 1을 반환

 

3. Constraint

1) 1 <= nums.length <= 104

2) -1000 <= nums[i] <= 1000

 

4. Example

Input: nums={1,7,3,6,5,6] -> Output: 3

설명:

- 왼쪽: nums[0] + nums[1] + nums[2] = 1 + 7 + 3 = 11

- 오른쪽: nums[4] + nums[5] = 5 + 6 = 11

- nums[3]을 기준으로 오른쪽과 왼쪽의 합이 같으므로 3을 반환한다.

 

5. Code

1) 첫 코드(2022/07/25)

int rsum = 0, lsum = 0, index = -1;
for(int i=0 ; i<nums.length ; i++){
    for(int j=0 ; j<i ; j++){
        lsum += nums[j]; // sum of left
    }
    for(int j=nums.length-1 ; j>i ; j--){
        rsum += nums[j]; // sum of right
    }
    if(rsum==lsum){
        index = i; break;
    }
    rsum = 0; lsum = 0;
} // for i

return index;