-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSummaryRanges.java
More file actions
39 lines (32 loc) · 878 Bytes
/
SummaryRanges.java
File metadata and controls
39 lines (32 loc) · 878 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Solution {
public List<String> summaryRanges(int[] nums) {
int n = nums.length;
ArrayList<String> res = new ArrayList<String>();
if(n == 0) return res;
int start = nums[0];
int end = nums[0];
for(int i=1; i < n; i++){
int ptr = nums[i];
if(ptr - nums[i-1] == 1){
end = nums[i];
continue;
}
res.add(toString(start, end));
start = nums[i];
end = nums[i];
}
res.add(toString(start, end));
return res;
}
public String toString(int a, int b){
StringBuilder sb = new StringBuilder();
if(a == b){
sb.append(a);
} else {
sb.append(a);
sb.append("->");
sb.append(b);
}
return sb.toString();
}
}