zoukankan      html  css  js  c++  java
  • leetcode-724-Find Pivot Index

    题目描述:

    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。

  • 相关阅读:
    最短路径-Dijkstra算法(转载)
    递归算法到非递归算法的转换
    向量点乘(内积)和叉乘(外积、向量积)概念及几何意义(转载)
    数据预处理之独热编码(One-Hot Encoding)(转载)
    MyEclipse中手工添加dtd支持
    怎样sublime显示文件夹
    sublime_Text3中snippet设置信息头(包括作者、日期)
    解决Sublime_Text不能安装插件的方法
    Python设置默认编码为UTF-8
    解决火狐启动缓慢的方法
  • 原文地址:https://www.cnblogs.com/chenjx85/p/9190512.html
Copyright © 2011-2022 走看看