首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode-724-Find Pivot Index

leetcode-724-Find Pivot Index

作者头像
chenjx85
发布2018-07-05 16:10:02
5240
发布2018-07-05 16:10:02
举报

题目描述:

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: 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:

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

代码如下:(附详解)

    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。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-06-16 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目描述:
  • 要完成的函数:
  • 说明:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档