Skip to content

Commit 45d29c3

Browse files
committed
[Easy] Title: 228. Summary Ranges - LeetCode
1 parent a31aaa1 commit 45d29c3

File tree

2 files changed

+73
-0
lines changed

2 files changed

+73
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
# [Easy] Summary Ranges
2+
3+
[문제 링크](https://leetcode.com/problems/summary-ranges/)
4+
5+
### 문제 μ„€λͺ…
6+
7+
You are given asorted uniqueinteger array`nums`.
8+
9+
Arange`[a,b]`is the set of all integers from`a`to`b`(inclusive).
10+
11+
Return*thesmallest sortedlist of ranges thatcover 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`.
12+
13+
Each range`[a,b]`in the list should be output as:
14+
15+
- `"a->b"`if`a != b`
16+
- `"a"`if`a == b`
17+
18+
Example 1:
19+
20+
```
21+
Input: nums = [0,1,2,4,5,7]
22+
Output: ["0->2","4->5","7"]
23+
```
24+
25+
Explanation: The ranges are:
26+
[0,2] --> "0->2"
27+
[4,5] --> "4->5"
28+
[7,7] --> "7"
29+
30+
Example 2:
31+
32+
```
33+
Input: nums = [0,2,3,4,6,8,9]
34+
Output: ["0","2->4","6","8->9"]
35+
```
36+
37+
Explanation: The ranges are:
38+
[0,0] --> "0"
39+
[2,4] --> "2->4"
40+
[6,6] --> "6"
41+
[8,9] --> "8->9"
42+
43+
Constraints:
44+
45+
- `0 <= nums.length <= 20`
46+
- `231 <= nums[i] <= 231 - 1`
47+
- All the values of`nums`areunique.
48+
- `nums`is sorted in ascending order.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
class Solution {
2+
public List<String> summaryRanges(int[] nums) {
3+
List<String> result = new ArrayList<>();
4+
int start = 0;
5+
6+
for(int i = 1; i < nums.length; i++) {
7+
if(nums[i - 1] + 1 != nums[i]) { // 이전값과 ν˜„μž¬κ°’μ΄ κ°™μ§€ μ•ŠμœΌλ©΄(연속xλ©΄ μ €μž₯)
8+
if(start == i - 1) { // μ‹œμž‘μΈλ±μŠ€λ°–μ— 없을 λ•Œ μ €μž₯
9+
result.add(String.valueOf(nums[start]));
10+
} else { // 연속 λ²”μœ„ μ €μž₯
11+
result.add(nums[start] + "->" + nums[i-1]);
12+
}
13+
// μ €μž₯ ν›„ μ‹œμž‘κ°’ μ΄ˆκΈ°ν™”
14+
start = i;
15+
}
16+
}
17+
// λ§ˆμ§€λ§‰ μ‹œμž‘κ°’ μΆ”κ°€ 계산
18+
if(start == nums.length - 1) { // 남은 μ‹œμž‘κ°’μ΄ λ§ˆμ§€λ§‰ 인덱슀일 λ•Œ
19+
result.add(String.valueOf(nums[start]));
20+
} else {
21+
result.add(nums[start] + "->" + nums[nums.length-1]);
22+
}
23+
return result;
24+
}
25+
}

0 commit comments

Comments
Β (0)