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].

自己的解法

class Solution {
    public int pivotIndex(int[] nums) {
        int right = 0;
        for (int i = 0; i < nums.length; i++) {
            int sumr = 0;
            int suml = 0;
            for (int j = 0; j < i; j++) {
                suml = suml + nums[j];
                right = suml;
            }
            for (int l = i + 1; l < nums.length; l++) {
                sumr = sumr + nums[l];
                
            }
            if (right == sumr) {
                    return i;
                } 
        }
        return -1;
    }
}

假设我们知道S是数字的总和,我们在索引i。如果我们知道索引i左边的数字总和,那么索引右边的另一个总和就是S - nums [i] - leftsum。因此,我们只需要知道leftsum来检查索引是否是恒定时间内的枢轴索引。让我们这样做:当我们迭代候选索引i时,我们将保持leftsum的正确值。

class Solution {
    public int pivotIndex(int[] nums) {
        int sum = 0, leftsum = 0;
        for (int x: nums) sum += x;
        for (int i = 0; i < nums.length; ++i) {
            if (leftsum == sum - leftsum - nums[i]) return i;
            leftsum += nums[i];
        }
        return -1;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,460评论 0 10
  • 被一个玻璃容器笼罩着,它可以看到外面斑斓的世界,外面的人也可以看见形单影只的它,但是无论这么靠近,都无法走到外面的...
    问微笑的月光阅读 154评论 0 0
  • js原生错误代码 js常见错误类型 (1)SyntaxError SyntaxError是解析代码时发生的语法错误...
    老头子_d0ec阅读 272评论 0 0
  • 如果说第一节第二节课讲得是战略,那么这次课讲得是实实在在的战术问题。框架布局是写好文章的第一步,就如同剑锋出鞘。如...
    踏雪折梅阅读 164评论 1 1