본문 바로가기
💻 LEETCODE

[LEETCODE] 1991. Find the Middle Index in Array

by 구라미 2022. 11. 24.

 

 

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:

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

 

내 풀이

class Solution:
    def findMiddleIndex(self, nums: List[int]) -> int:
        r_idx = len(nums) - 1
        l_idx = 0
        
        if len(set(nums)) == 1:
            return 0
        
        if len(nums) == 2:
            return -1
        
        for idx, num in enumerate(nums):
            if idx == 0:
                right = nums[r_idx]
                left = nums[l_idx]
            else:
                if right > left:
                    l_idx += 1
                    left += nums[l_idx]
                if left > right:
                    r_idx -= 1
                    right += nums[r_idx]
        if right == left:
            return l_idx
        else:
            return -1

두개의 포인터를 갖고 해결하는걸 생각했는데 테스트 케이스 몇개만 맞추고 결국엔 실패했다.

 

다른 풀이

def findMiddleIndex(self, nums: List[int]) -> int:               
	leftSum = 0
	rightSum = sum(nums)

	for i in range(len(nums)):
		if leftSum == rightSum - nums[i]:
			return i

		leftSum += nums[i]
		rightSum -= nums[i]

	return -1

숫자배열의 합을 전부더해서 순서대로 차감하는 방식이다. 좀만더 사고력이 있었다면 좀만더 생각했더라면...ㅠㅠ 너무 아쉬워

 

'💻 LEETCODE' 카테고리의 다른 글

[LEETCODE] Diagonal Traverse  (0) 2022.11.30
[LEETCODE] 5. Longest Palindromic Substring  (0) 2022.11.30
[LEETCODE] 20. Valid Parentheses  (0) 2022.11.23
[LEETCODE] 14. Longest Common Prefix  (0) 2022.11.22
[LEETCODE] 9. Palindrome Number  (0) 2022.11.22

댓글