본문 바로가기

LeetCode

3046. Split the Array / TypeScirpt

You are given an integer array nums of even length. You have to split the array into two parts nums1 and nums2 such that:

  • nums1.length == nums2.length == nums.length / 2.
  • nums1 should contain distinct elements.
  • nums2 should also contain distinct elements.

Return true if it is possible to split the array, and false otherwise.

 

Example 1:

Input: nums = [1,1,2,2,3,4]
Output: true
Explanation: One of the possible ways to split nums is nums1 = [1,2,3] and nums2 = [1,2,4].

Example 2:

Input: nums = [1,1,1,1]
Output: false
Explanation: The only possible way to split nums is nums1 = [1,1] and nums2 = [1,1]. Both nums1 and nums2 do not contain distinct elements. Therefore, we return false.

 

출처 : https://leetcode.com/problems/split-the-array/description/

 

풀이

function isPossibleToSplit(nums: number[]): boolean {
    const map = Array(101);
    for (const num of nums)
        if (map[num]) {
            if (++map[num] > 2) return false;
        } else map[num] = 1;
    return true;
};

 

배열 nums가 주어졌을 때, 배열의 각 원소가 1번씩만 등장하는지 확인하는 함수

Ex) nums = [1,1,2,2,3,4]

 

배열을 순회하면서 동작 확인

  1. 숫자 1 (첫 번째 등장)
    • num = 1
    • map[1]은 undefined이므로, map[1] = 1로 설정
    • map 배열: [undefined, 1, undefined, ..., undefined]
    • 반환 값: 계속 진행
  2. 숫자 1 (두 번째 등장)
    • num = 1
    • map[1]은 1이므로, ++map[1]는 2로 증가.
    • map[1] > 2는 false이므로, 계속 진행
    • map 배열: [undefined, 2, undefined, ..., undefined]
    • 반환 값: 계속 진행
  3. 숫자 2 (첫 번째 등장)
    • num = 2
    • map[2]은 undefined이므로, map[2] = 1로 설정
    • map 배열: [undefined, 2, 1, undefined, ..., undefined]
    • 반환 값: 계속 진행
  4. 숫자 2 (두 번째 등장)
    • num = 2
    • map[2]은 1이므로, ++map[2]는 2로 증가
    • map[2] > 2는 false이므로, 계속 진행
    • map 배열: [undefined, 2, 2, undefined, ..., undefined]
    • 반환 값: 계속 진행
  5. 숫자 3 (첫 번째 등장)
    • num = 3
    • map[3]은 undefined이므로, map[3] = 1로 설정
    • map 배열: [undefined, 2, 2, 1, undefined, ..., undefined]
    • 반환 값: 계속 진행
  6. 숫자 4 (첫 번째 등장)
    • num = 4
    • map[4]은 undefined이므로, map[4] = 1로 설정.
    • map 배열: [undefined, 2, 2, 1, 1, ..., undefined]
    • 반환 값: 계속 진행

 

최종 결과

모든 숫자가 최대 2번 등장했기 때문에 함수는 true를 반환