724. Find Pivot Index

406 篇文章 0 订阅
406 篇文章 0 订阅

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.
这里写图片描述
找到一个分界点,使得分界点前的所有的数字的和与其后的所有数字的和是相等的。
第一个数字和最后一个数字也可以是分界点(和为0即可)。

2,题目思路
可以用暴力的方法来实现,但是人类不能总是以暴力解决问题。
另一种思路便是,先求出整个数组的和。然后再对数组遍历,当部分和的2倍于整个数组的和减去分界数字时相等,则返回分界数字所对应的索引值。

3,程序源码

class Solution {
public:
    int pivotIndex(vector<int>& nums) {
        int total = 0, sum = 0;
        for(auto num : nums) total += num;
        for(int i=0;i<nums.size();sum += nums[i++])
        {
            if(sum*2 == total - nums[i])
                return i;
        }
        return -1;
    }
};

值得注意的是,将sum的更新和i的更新写在for循环中,可以巧妙的实现分界数字是第一个时候的情况:
去掉第一个,剩下的所有数字的和为0,则第一个就是分界数字。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值