LeetCode-Summary Ranges
Given a sorted integer array without duplicates, return the summary of its ranges.
For example, given [0,1,2,4,5,7]
, return ["0->2","4->5","7"].
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
Solution:
1 public class Solution { 2 public String getRangeStr(int start, int end){ 3 if (start == end){ 4 return Integer.toString(start); 5 } else { 6 StringBuilder builder = new StringBuilder(); 7 builder.append(start); 8 builder.append("->"); 9 builder.append(end); 10 return builder.toString(); 11 } 12 } 13 public List<String> summaryRanges(int[] nums) { 14 List<String> resList = new LinkedList<String>(); 15 if (nums.length==0) return resList; 16 17 int start = nums[0]; 18 int end = nums[0]; 19 20 for (int i=1;i<nums.length;i++){ 21 if (nums[i] <= end) continue; 22 23 if (nums[i]==end+1){ 24 end = nums[i]; 25 } else { 26 resList.add(getRangeStr(start,end)); 27 start = nums[i]; 28 end = nums[i]; 29 } 30 } 31 32 resList.add(getRangeStr(start,end)); 33 return resList; 34 } 35 }