Skip to content

Commit e447e71

Browse files
committed
add solution of problem 228: summary ranges
1 parent 2fdf4f6 commit e447e71

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

SummaryRanges228/README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Given a sorted integer array without duplicates, return the summary of its ranges.
2+
3+
For example, given `[0,1,2,4,5,7]`, return `["0->2","4->5","7"]`.

SummaryRanges228/Solution.java

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
public class Solution {
2+
public List<String> summaryRanges(int[] nums) {
3+
List<String> result = new ArrayList<String>();
4+
if (nums == null)
5+
return result;
6+
7+
int idx = 0;
8+
while (idx < nums.length) {
9+
int startIdx = idx;
10+
int endIdx = idx;
11+
12+
while (idx < nums.length - 1 && nums[idx] + 1 == nums[idx + 1]) {
13+
endIdx++;
14+
idx++;
15+
}
16+
17+
String s;
18+
if (endIdx > startIdx) {
19+
s = "" + nums[startIdx] + "->" + nums[endIdx];
20+
} else {
21+
s = "" + nums[startIdx];
22+
}
23+
24+
result.add(s);
25+
26+
if (idx == nums.length - 1)
27+
break;
28+
else
29+
idx++;
30+
}
31+
32+
return result;
33+
}
34+
}

0 commit comments

Comments
 (0)