【问题标题】:I tried the problem Leetcode-724 (Pivot index) - how can I correct my approach?我尝试了 Leetcode-724 (Pivot index) 这道题——我该如何纠正我的方法?
【发布时间】:2023-01-09 05:50:26
【问题描述】:

问题:

给定一个整数数组 nums,计算该数组的主元索引。

主元索引是指严格位于索引左侧的所有数字之和等于严格位于索引右侧的所有数字之和的索引。

如果索引位于数组的左边缘,则左边的和为 0,因为左边没有元素。这也适用于数组的右边缘。

返回最左边的枢轴索引。如果不存在这样的索引,则返回 -1。

代码:

class Solution {

    public int sumA(int a, int b, int[] s){
            int res=0;
            for(int i = a; i<b; i++){
                res= res + s[i];
            }
            return res;
        }


    public int pivotIndex(int[] nums) {
        int sum = 0;
        int i=0;
        int flag = 0;
        int x = nums.length;

        sum= sumA(0, x, nums);

        for(i = 1; i < nums.length; i++){
            if((sum - nums[i] - sumA(0, i-1, nums)) 
            == (sumA(0, i-1, nums))){
                flag=1;
                break;
            }
        }

        if(flag == 1) return i;
        else if((i==0) ||(i==x)) return 0;
        else return -1;
        
    }
}

【问题讨论】:

  • 您有什么问题或疑虑?
  • 当你的索引i是0或x时,为什么你返回0?
  • 谢谢你们,我解决了这个问题,我是编码的初学者,我希望变得更好!

标签: java


【解决方案1】:

给定的代码计算数组中所有元素的总和,然后检查每个索引是否该索引左侧的元素总和等于该索引右侧的元素总和。如果是这种情况,它会返回索引。

这种方法有几个问题:

没有使用 sumA 方法,因此可以将其删除。 该方法不检查主元索引是在数组的左边缘还是右边缘,因此在这些情况下它可能会返回不正确的结果。 该方法只检查第一个主元索引并返回它,但数组中可以有多个主元索引。它应该返回最左边的枢轴索引。 要解决这些问题,可以对代码进行以下更改:

将变量 leftSum 初始化为 0,将变量 rightSum 初始化为数组中所有元素的总和。 从左到右遍历数组中的元素。 对于每个索引,将该索引处的元素添加到 leftSum 并从 rightSum 中减去它。 如果 leftSum 等于 rightSum,则返回索引。 如果到达数组末尾但未找到主元索引,则返回 -1。 更新后的代码如下所示:

class Solution {
    public int pivotIndex(int[] nums) {
        // Initialize leftSum to 0 and rightSum to the sum of all elements in the array
        int leftSum = 0;
        int rightSum = 0;
        for (int num : nums) {
            rightSum += num;
        }

        // Iterate over the elements in the array from left to right
        for (int i = 0; i < nums.length; i++) {
            // Add the element at the current index to leftSum and subtract it from rightSum
            leftSum += nums[i];
            rightSum -= nums[i];

            // If leftSum is equal to rightSum, return the index
            if (leftSum == rightSum) {
                return i;
            }
        }

        // If the end of the array is reached without finding a pivot index, return -1
        return -1;
    }
}

【讨论】:

  • 非常感谢,这真是信息丰富!
猜你喜欢
  • 1970-01-01
  • 2023-03-25
  • 2016-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-09
  • 2019-08-10
相关资源
最近更新 更多