724. 寻找数组的中心下标

Leetcode题目:前缀和

给你一个整数数组 nums ,请计算数组的 中心下标 。

数组 中心下标 是数组的一个下标,其左侧所有元素相加的和等于右侧所有元素相加的和。

如果中心下标位于数组最左端,那么左侧数之和视为 0 ,因为在下标的左侧不存在元素。这一点对于中心下标位于数组最右端同样适用。

如果数组有多个中心下标,应该返回 最靠近左边 的那一个。如果数组不存在中心下标,返回 -1 。

示例 1:

输入:nums = [1, 7, 3, 6, 5, 6]
输出:3
解释:
中心下标是 3 。
左侧数之和 sum = nums[0] + nums[1] + nums[2] = 1 + 7 + 3 = 11 ,
右侧数之和 sum = nums[4] + nums[5] = 5 + 6 = 11 ,二者相等。

示例 2:

输入:nums = [1, 2, 3]
输出:-1
解释:
数组中不存在满足此条件的中心下标。

示例 3:

输入:nums = [2, 1, -1]
输出:0
解释:
中心下标是 0 。
左侧数之和 sum = 0 ,(下标 0 左侧不存在元素),
右侧数之和 sum = nums[1] + nums[2] = 1 + -1 = 0 。

提示:

  • 1 <= nums.length <= 104
  • -1000 <= nums[i] <= 1000

解题思路

前缀和

求数组某个区间内的和,那就肯定是用前缀和了。那么先把前缀和计算出来。

class Solution {
public:
    int pivotIndex(vector<int>& nums) {
        vector<int>sum;
        int size=nums.size();
        sum.resize(size+1);
        for(int i=0;i<size;i++)
            sum[i+1]=sum[i]+nums[i];
      //TODO:计算中心下标

    }
};

接下来看看中心下标。左部比较好处理,直接就是数组前n项和。简单来说,假设要求的下标为x。那么我们实际上要判断的是什么时候会有

a0+a1+…+ax-1=ax+1+…+an

满足该条件的x就是我们要找的中心下标。

class Solution {
public:
    int pivotIndex(vector<int>& nums) {
        vector<int>sum;
        int size=nums.size();
        sum.resize(size+1);
        for(int i=0;i<size;i++)
            sum[i+1]=sum[i]+nums[i];
                                   
        for(int index=0;index<size;index++)
            if(sum[size]-sum[index]==sum[index+1])
                return index;
        return -1;
    }
};
Subscribe
提醒
0 评论
Inline Feedbacks
View all comments
0
在此留下你的评论x