[Chetuzai's Algorithm Cultivation Tour] LeetCode1991: Find the middle position in the array

Offer arrives, dig friends to pick up! I am participating in the 2022 Spring Recruitment series of activities - swipe questions and punch cards. Click to view the details of the activities .

1. Description of the topic

Given an integer array nums with subscripts starting from 0, please find the leftmost middle position middleIndex (that is, the one with the smallest subscript of all possible middle positions).

The middle position middleIndex is such that nums[0] + nums[1] + ... + nums[middleIndex-1] == nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length -1] Array subscript.

If middleIndex == 0 , the sum of the left part is defined as 0 . Similarly, if middleIndex == nums.length - 1 , the sum of the right part is defined as 0 .

Please return the leftmost middleIndex that satisfies the above conditions. If there is no such intermediate position, please return -1 .

示例1:

输入: nums = [2,3,-1,8,4]
输出: 3
解释:
下标 3 之前的数字和为:2 + 3 + -1 = 4
下标 3 之后的数字和为:4 = 4
复制代码

示例2:

输入: nums = [1,-1,4]
输出: 2
解释:
下标 2 之前的数字和为:1 + -1 = 0
下标 2 之后的数字和为:0
复制代码

示例3:

输入: nums = [2,5]
输出: -1
解释:
不存在符合要求的 middleIndex 。
复制代码

示例4:

输入: nums = [1]
输出: 0
解释:
下标 0 之前的数字和为:0
下标 0 之后的数字和为:0
复制代码

hint:

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

2. Thought analysis

The sum of all elements of the array is sum, and when the ith element is traversed, the sum of its left elements is left, that is, the sum of its right elements is sum - nums[i] - left. The left and right elements are equal, that is, left = sum - nums[i] - left, that is, 2 * left + nums[i] = sum.

When there are no elements to the left or right of the center index, zero items are added, which is mathematically called [null sum]. In programming we agree [null and zero].

3. AC Code

/**
 * @param {number[]} nums
 * @return {number}
 */
var findMiddleIndex = function(nums) {
    let sum = 0, left = 0;
    // 先对整个数组求和
    sum = nums.reduce((a, b) => a + b, 0);
    // 遍历数组,如果left * 2 + 当前数组值的和为sum,则找到了中心索引并返回,否则继续遍历
    for (let i = 0; i < nums.length; i++) {
        if (left * 2 + nums[i] === sum) {
            return i
        } else {
            left += nums[i]
        }
    }
    // 找不到返回 -1
    return -1
};
复制代码

4. Summary

This question mainly examines 前缀和.

Complexity Analysis

  • Time complexity: O(n), where n is the length of the array.
  • Space complexity: O(1).

Guess you like

Origin juejin.im/post/7079016923711127565