LEETCODE: 724. Find Pivot Index

来源:互联网 发布:lol免费皮肤软件 编辑:程序博客网 时间:2024/05/21 21:01

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.

Example 1:

Input: nums = [1, 7, 3, 6, 5, 6]Output: 3Explanation: The sum of the numbers to the left of index 3 (nums[3] = 6) is equal to the sum of numbers to the right of index 3.Also, 3 is the first index where this occurs.

Example 2:

Input: nums = [1, 2, 3]Output: -1Explanation: There is no index that satisfies the conditions in the problem statement.

Note:

The length of nums will be in the range [0, 10000].
Each element nums[i] will be an integer in the range [-1000, 1000].

难度:easy

看到这个题目,坐下来想5分钟。最简单的方法,就是遍历所有位置,然后分别计算左边所有元素的和,以及右边所有元素的和,如果它们相等,那么符合条件,返回。

for number in nums    计算左边元素之和 nums[0] + nums[1] + nums[left]    计算右边元素之和 nums[right] + nums[right+1] + nums[n-1]    if 左边的和 == 右边的和        返回 元素的 index

但是每次都计算左/右边元素之和,效率不高。如果数组是从 0 一直遍历到 n-1 的,并且已知他们的和为 sum。那么:

位置 左边的和 右边的和 0 0 sum - num[0] 1 num[0] sum - num[0] - num[1] 2 num[0] + num[1] sum - num[0] - num[1] - num[2] 3 num[0] + num[1] + num[2] sum - num[0] - num[1] - num[2]- num[3]

由此可见,每一步的左边之和,可以是 上一步的左边之和 加上 当前的左边元素 的和。每一步的右边之和,可以是 上一步的右边之和 减去 当前元素 的结果。

代码如下:

class Solution {public:    int pivotIndex(vector<int>& nums) {        int n = nums.size();        int sum = 0;        for(int ii = 0; ii < n; ii ++) {            sum += nums[ii];        }        int leftSum = 0;        int rightSum = sum;        for(int ii = 0; ii < n; ii ++) {            leftSum += ii > 0 ? nums[ii - 1] : 0;            rightSum -= nums[ii];            if(leftSum == rightSum) {                return ii;            }        }        return -1;    }};
原创粉丝点击