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]인 경우:
- i = 0, j = 0:
- nums[0] + 1 === nums[1] -> j = 1
- i = 1, j = 1:
- nums[1] + 1 === nums[2] -> j = 2
- i = 2, j = 2:
- nums[2] + 1 !== nums[3]
- arr.push("0->2"), j = 0
- i = 3, j = 0:
- nums[3] + 1 === nums[4] -> j = 1
- i = 4, j = 1:
- nums[4] + 1 !== nums[5]
- arr.push("4->5"), j = 0
- i = 5, j = 0:
- 마지막 요소: arr.push("7")
최종적으로 arr는 ["0->2", "4->5", "7"]가 되어 반환
'LeetCode' 카테고리의 다른 글
| 563. Binary Tree Tilt (0) | 2024.05.24 |
|---|---|
| 1640. Check Array Formation Through Concatenation / TypeScript (0) | 2024.05.21 |
| 2932. Maximum Strong Pair XOR I / TypeScript (0) | 2024.05.19 |
| 2562. Find the Array Concatenation Value / TypeScript (0) | 2024.05.18 |
| 455. Assign Cookies / TypeScript (0) | 2024.05.17 |