carloscn / structstudy

Leetcode daily trainning by using C/C++/RUST programming.
4 stars 1 forks source link

leetcode1991: Find the Middle Index in Array #318

Open carloscn opened 1 year ago

carloscn commented 1 year ago

Decription

Given a 0-indexed integer array nums, find the leftmost middleIndex (i.e., the smallest amongst all the possible ones).

A middleIndex is an index where nums[0] + nums[1] + ... + nums[middleIndex-1] == nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1].

If middleIndex == 0, the left side sum is considered to be 0. Similarly, if middleIndex == nums.length - 1, the right side sum is considered to be 0.

Return the leftmost middleIndex that satisfies the condition, or -1 if there is no such index.

Example 1:

Input: nums = [2,3,-1,8,4] Output: 3 Explanation: The sum of the numbers before index 3 is: 2 + 3 + -1 = 4 The sum of the numbers after index 3 is: 4 = 4

Example 2:

Input: nums = [1,-1,4] Output: 2 Explanation: The sum of the numbers before index 2 is: 1 + -1 = 0 The sum of the numbers after index 2 is: 0

Example 3:

Input: nums = [2,5] Output: -1 Explanation: There is no valid middleIndex.

Constraints:

Note: This question is the same as 724: https://leetcode.com/problems/find-pivot-index/

carloscn commented 1 year ago

Analysis

pub fn find_middle_index(nums: Vec<i32>) -> i32
{
    if nums.len() < 3 {
        return -1;
    }

    let mut ret:i32 = -1;
    let mut sum_left:i32;
    let mut sum_right:i32;
    let left:usize = 0;
    let right:usize = nums.len();

    for mid in 1..nums.len() {
        sum_left = 0;
        sum_right = 0;

        for i in left..mid {
            sum_left += nums[i];
        }
        for i in (mid + 1)..right {
            sum_right += nums[i];
        }
        if sum_left == sum_right {
            ret = mid as i32;
            break;
        }
    }

    return ret;
}
carloscn commented 1 year ago

Code

https://review.gerrithub.io/c/carloscn/structstudy/+/1168222 https://github.com/carloscn/structstudy/commit/d37734a66a2a2514f089ce7f9903ff710c6e4714