-
Notifications
You must be signed in to change notification settings - Fork 0
/
SummaryRanges.java
49 lines (40 loc) · 1.39 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 arrays;
import utils.LeetCode;
import utils.Level;
import java.util.ArrayList;
import java.util.List;
@LeetCode(no = 228,
level = Level.EASY,
title = "Summary Ranges",
url = "https://leetcode.com/problems/summary-ranges/")
public class SummaryRanges {
public static void main(String[] args) {
SummaryRanges s= new SummaryRanges();
System.out.println(s.summaryRanges(new int []{0,2,3,4,6,8,9}));
}
public List<String> summaryRanges(int[] nums) {
List<String>result=new ArrayList<>();
if (nums.length==0) return result;
int prev=nums[0];
StringBuffer sb= new StringBuffer(String.valueOf(nums[0]));
for(int i=1; i<nums.length;i++){
System.out.println(nums[i]);
if( prev!=nums[i] && prev+1 !=nums[i]){
if(!sb.toString().equals(String.valueOf(prev)) ){
sb.append("->");
sb.append(String.valueOf(prev));
}
result.add(sb.toString());
sb= new StringBuffer(String.valueOf(nums[i]));
// System.out.println(sb.toString());
}
prev=nums[i];
}
if(!sb.toString().equals(String.valueOf(prev)) ){
sb.append("->");
sb.append(String.valueOf(prev));
}
result.add(sb.toString());
return result;
}
}