정수 배열 nums가 주어졌을 때, 이 배열의 피벗 인덱스를 계산하세요.
피벗 인덱스는 해당 인덱스를 기준으로 왼쪽의 모든 숫자의 합이 오른쪽의 모든 숫자의 합과 동일한 인덱스를 나타냅니다.
만약 인덱스가 배열의 왼쪽 끝에 있다면, 왼쪽의 합은 0이 됩니다. 이는 배열의 오른쪽 끝에도 적용됩니다.
가장 왼쪽에 있는 피벗 인덱스를 반환하세요. 만약 이러한 인덱스가 없다면 -1을 반환하세요.
Given an array of integers nums, calculate the pivot index of this array.
The pivot index is the index where the sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers strictly to the index's right.
If the index is on the left edge of the array, then the left sum is 0 because there are no elements to the left. This also applies to the right edge of the array.
Return the leftmost pivot index. If no such index exists, return -1.
Example 1:
Input: nums = [1,7,3,6,5,6]
Output: 3
Explanation:
The pivot index is 3.
Left sum = nums[0] + nums[1] + nums[2] = 1 + 7 + 3 = 11
Right sum = nums[4] + nums[5] = 5 + 6 = 11
Example 2:
Input: nums = [1,2,3]
Output: -1
Explanation:
There is no index that satisfies the conditions in the problem statement.
Example 3:
Input: nums = [2,1,-1]
Output: 0
Explanation:
The pivot index is 0.
Left sum = 0 (no elements to the left of index 0)
Right sum = nums[1] + nums[2] = 1 + -1 = 0
문제 요약:
정수 배열 nums가 주어지고, 피벗 인덱스를 찾아야 합니다. 피벗 인덱스는 해당 인덱스를 기준으로 왼쪽의 합과 오른쪽의 합이 동일한 지점을 나타냅니다. 만약 그런 인덱스가 없다면 -1을 반환합니다.
풀이과정 설명:
class Solution {
public int pivotIndex(int[] nums) {
int totalSum = 0;
int leftSum = 0;
for (int num : nums) {
totalSum += num;
}
for (int i = 0; i < nums.length; i++) {
if (leftSum == totalSum - leftSum - nums[i]) {
return i;
}
leftSum += nums[i];
}
return -1;
}
}
풀이과정 설명:
class Solution {
public int pivotIndex(int[] nums) {
int sumLeft = 0;
int sumRight = -nums[0];
for(int num : nums){
sumRight += num;
}
for(int i = 0; i < nums.length; i++){
if(sumLeft == sumRight) return i;
sumLeft += nums[i];
if(i + 1 < nums.length){
sumRight -= nums[i+1];
}
}
return -1;
}
}
2390. Removing Stars From a String (0) | 2023.11.16 |
---|---|
1657. Determine if Two Strings Are Close (0) | 2023.11.13 |
1732. Find the Highest Altitude (0) | 2023.11.11 |
1493. Longest Subarray of 1's After Deleting One Element (0) | 2023.11.06 |
1004. Max Consecutive Ones III (0) | 2023.11.06 |