-
Notifications
You must be signed in to change notification settings - Fork 1
/
SummaryRanges.java
49 lines (43 loc) · 1.36 KB
/
SummaryRanges.java
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
40
41
42
43
44
45
46
47
48
49
package com.smlnskgmail.jaman.leetcodejava.easy;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
// https://leetcode.com/problems/summary-ranges/
public class SummaryRanges {
private final int[] input;
public SummaryRanges(int[] input) {
this.input = input;
}
public List<String> solution() {
if (input.length == 0) {
return Collections.emptyList();
}
List<String> result = new ArrayList<>();
int start = input[0];
int end = start;
for (int i = 1; i < input.length; i++) {
int num = input[i];
if (end + 1 == num) {
end = num;
} else {
if (start == end) {
result.add(String.valueOf(start));
} else {
StringBuilder range = new StringBuilder();
range.append(start).append("->").append(end);
result.add(range.toString());
}
start = num;
end = start;
}
}
if (start == end) {
result.add(String.valueOf(start));
} else {
StringBuilder range = new StringBuilder();
range.append(start).append("->").append(end);
result.add(range.toString());
}
return result;
}
}