LeetCode Note Java 00724:Find Pivot Index

找出輸入的 intArray nums 的 Pivot Index (索引的左右兩邊總和相同)。

題目

Find Pivot Index Easy

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.

我的解法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public int pivotIndex(int[] nums) {
for (int i = 0; i < nums.length; i++) {
int left = 0, right = 0;
for (int j = 0; j < i; j++) {
left += nums[j];
}
for (int j = i +1; j < nums.length; j++) {
right += nums[j];
}
if (left == right) {
return i;
}
}
return -1;
}
}

用了粗暴方式作答,Runtime 拉得很長。

檢討

別人寫得 Runtime 就極短。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// Runtime: 1 ms, faster than 92.94% of Java online submissions for Find Pivot Index.
// Time Complexity : O(n)
class Solution {
public int pivotIndex(int[] nums) {
// Initialize total sum of the given array...
int totalSum = 0;
// Initialize 'leftsum' as sum of first i numbers, not including nums[i]...
int leftsum = 0;
// Traverse the elements and add them to store the totalSum...
for (int ele : nums)
totalSum += ele;
// Again traverse all the elements through the for loop and store the sum of i numbers from left to right...
for (int i = 0; i < nums.length; leftsum += nums[i++])
// sum to the left == leftsum.
// sum to the right === totalSum - leftsum - nums[i]..
// check if leftsum == totalSum - leftsum - nums[i]...
if (leftsum * 2 == totalSum - nums[i])
return i; // Return the pivot index...
return -1; // If there is no index that satisfies the conditions in the problem statement...
}
}

避開了多層回圈,果然還是要多看別人的解答來擴編我僵化的腦袋。

參考資料

Very Easy || 100% || Fully Explained || Java, C++, Python, JS, Python3