Leetcode 724: Find Pivot Index

问题描述:
Given an array of integers nums, calculate the pivot index of this array.
The pivot index is the index where the sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers strictly to the index’s right.
If the index is on the left edge of the array, then the left sum is 0 because there are no elements to the left. This also applies to the right edge of the array.
Return the leftmost pivot index. If no such index exists, return -1.

pivot index: 它左侧的子数组的和=它右侧的子数组的和,这个位置(index)被定义为pivot index
对于左侧/右侧边界,左侧/右侧子数组不存在,我们认为和为0
若没有,则返回-1

思路:
一边循环数组求和(sum)
然后逐个元素遍历,若其左侧之和其右侧之和,即sum_leftsum-它自己-sum_left, 我们返回该脚标

代码如下:

class Solution {
    public int pivotIndex(int[] nums) {
        int sum=0;
        int left_sum=0;
        for(int i=0; i<nums.length; i++){
            sum+=nums[i];
        }
        for(int i=0; i<nums.length;i++){
            if(left_sum==sum-left_sum-nums[i]){
                return i;
            }
            left_sum+=nums[i];
        }
        return -1;
    }
}

时间复杂度: O(n)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值