본문 바로가기

LeetCode

228. Summary Ranges / TypeScript

You are given a sorted unique integer array nums.

A range [a,b] is the set of all integers from a to b (inclusive).

Return the smallest sorted list of ranges that cover all the numbers in the array exactly. That is, each element of nums is covered by exactly one of the ranges, and there is no integer x such that x is in one of the ranges but not in nums.

Each range [a,b] in the list should be output as:

  • "a->b" if a != b
  • "a" if a == b

 

Example 1:

Input: nums = [0,1,2,4,5,7]
Output: ["0->2","4->5","7"]
Explanation: The ranges are:
[0,2] --> "0->2"
[4,5] --> "4->5"
[7,7] --> "7"

Example 2:

Input: nums = [0,2,3,4,6,8,9]
Output: ["0","2->4","6","8->9"]
Explanation: The ranges are:
[0,0] --> "0"
[2,4] --> "2->4"
[6,6] --> "6"
[8,9] --> "8->9"

 

 

출처 : https://leetcode.com/problems/summary-ranges/description/

 

 

풀이

 

function summaryRanges(nums: number[]): string[] {
    const arr: string[] = []
    for (let i = 0, j = 0; i < nums.length; i++) {
        if (nums[i] + 1 === nums[i + 1]) j++
        else {
            arr.push(nums[i - j] !== nums[i] ? `${nums[i - j]}->${nums[i]}` : `${nums[i]}`)
            j = 0
        }
    }
    return arr
};

 

 

정렬된 숫자 배열에서 연속된 숫자 범위를 문자열 형식으로 요약하여 반환

 

예를 들어, nums가 [0, 1, 2, 4, 5, 7]인 경우:

  1. i = 0, j = 0:
    • nums[0] + 1 === nums[1] -> j = 1
  2. i = 1, j = 1:
    • nums[1] + 1 === nums[2] -> j = 2
  3. i = 2, j = 2:
    • nums[2] + 1 !== nums[3]
    • arr.push("0->2"), j = 0
  4. i = 3, j = 0:
    • nums[3] + 1 === nums[4] -> j = 1
  5. i = 4, j = 1:
    • nums[4] + 1 !== nums[5]
    • arr.push("4->5"), j = 0
  6. i = 5, j = 0:
    • 마지막 요소: arr.push("7")

최종적으로 arr는 ["0->2", "4->5", "7"]가 되어 반환