Given an array of integers nums, write a method that returns the “pivot” index of this array.
We define the pivot index as the index where the sum of the numbers to the left of the index is equal to the sum of the numbers to the right of the index.
If no such index exists, we should return -1. If there are multiple pivot indexes, you should return the left-most pivot index.
原题链接:https://leetcode.com/explore/learn/card/array-and-string/201/introduction-to-array/1144/
就是找到一个索引,使之左侧所有元素相加的和等于右侧所有元素相加的和
先求出前缀和,index处的左侧元素等于相加和为index - 1 处的前缀和,右侧元素相加和为所有元素之和与 index 车的 前缀和之差。
c++代码
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int pivotIndex(vector<int>& nums) {
int sum = 0;
vector<int> presum;
presum.push_back(sum);
for (int i = 0; i < nums.size(); i++) {
sum += nums[i];
presum.push_back(sum);
}
int size = presum.size();
for (int i = 1; i < size; i++) {
if (presum[i - 1] == presum[size - 1] - presum[i]) {
return i - 1;
}
}
return -1;
}
};
int main() {
int arr[] = {-1,-1,0,1,1,0};
vector<int> vec1(arr, arr + 6);
cout << Solution().pivotIndex(vec1) << endl;
return 0;
}
Java代码
class Solution {
public int pivotIndex(int[] nums) {
int[] sum = new int[nums.length + 1];
sum[0] = 0;
for (int i = 0; i < nums.length; i++)
sum[i+1] = sum[i] + nums[i];
for (int i = 1; i < sum.length; i++) {
int left = sum[i - 1];
int right = sum[sum.length - 1] - sum[i];
if (left == right)
return i - 1;
}
return -1;
}
public static void main(String[] args) {
Solution res = new Solution();
int[] arr = {-1,-1,0,1,1,0};
System.out.println(res.pivotIndex(arr));
}
}