• 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。

  • 相关阅读:
    Java并发编程:线程池的使用
    AlarmManager与PendingIntent
    ConnectivityManager与检查网络连接的使用
    IntentService的使用
    Service(Local Service)简介
    Looper、Hander、HandlerThread
    XML_PULL解析
    android AsyncTask 的使用(转载)
    android 连接网络的简单实例
    xml drawable
  • 原文地址:https://www.cnblogs.com/chenjx85/p/9190512.html
Copyright © 2020-2023  润新知