1,题目要求
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.
找到一个分界点,使得分界点前的所有的数字的和与其后的所有数字的和是相等的。
第一个数字和最后一个数字也可以是分界点(和为0即可)。
2,题目思路
可以用暴力的方法来实现,但是人类不能总是以暴力解决问题。
另一种思路便是,先求出整个数组的和。然后再对数组遍历,当部分和的2倍于整个数组的和减去分界数字时相等,则返回分界数字所对应的索引值。
3,程序源码
class Solution {
public:
int pivotIndex(vector<int>& nums) {
int total = 0, sum = 0;
for(auto num : nums) total += num;
for(int i=0;i<nums.size();sum += nums[i++])
{
if(sum*2 == total - nums[i])
return i;
}
return -1;
}
};
值得注意的是,将sum的更新和i的更新写在for循环中,可以巧妙的实现分界数字是第一个时候的情况:
去掉第一个,剩下的所有数字的和为0,则第一个就是分界数字。