leetcode-724-Find Pivot Index

2018-07-05 16:10:02 浏览数 (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.

Example 1:

代码语言:javascript复制
Input: 
nums = [1, 7, 3, 6, 5, 6]
Output: 3
Explanation: 
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:

代码语言:javascript复制
Input: 
nums = [1, 2, 3]
Output: -1
Explanation: 
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].

要完成的函数:

int pivotIndex(vector<int>& nums) 

说明:

1、这道题给定一个vector,要求找到vector中的中轴元素。中轴元素的定义是:左边元素的和等于右边元素的和。

vector中的元素值在[-1000,1000]之间。

2、这道题不难,我们用类似窗口滑动的想法,从左至右逐个判断是否是中轴元素就可以了。

代码如下:(附详解)

代码语言:javascript复制
    int pivotIndex(vector<int>& nums) 
    {
        int s1=nums.size();
        if(s1==0)return -1;//边界处理,nums是一个空的vector
        int suml=0,sumr=accumulate(nums.begin(),nums.end(),0)-nums[0],pos=0;//sumr等于从nums[1]开始到末尾的所有元素之和
        while(pos<s1)
        {
            if(suml==sumr)
                return pos;
            pos  ;
            suml =nums[pos-1];//窗口滑动,suml加上一个新的值
            sumr-=nums[pos];//窗口滑动,sumr减去一个值
        }
        return -1;
    }

上述代码十分简洁,实测 43ms,beats 72.02% of cpp submissions。

0 人点赞