LeetCode Problem

228. Summary Ranges Link to LeetCode You are given a sorted unique integer array nums. A range [a,b] is the set of all integers from a to b (inclusive). Return the smallest sorted list of ranges that cover all the numbers in the array exactly. That is, each element of nums is covered by exactly one of the ranges, and there is no integer x such that x is in one of the ranges but not in nums. Input: nums = [0,1,2,4,5,7] Output: ["0->2","4->5","7"] Explanation: The ranges are: [0,2] --> "0->2" [4,5] --> "4->5" [7,7] --> "7" Analysis When iterating over the array, two values need to be tracked: 1) the first value of a new range and 2) the previous value in the range. public List< String> summaryRanges(int[] nums) { List< String> result = new ArrayList< String>(); if(nums == null || nums.length==0) return result; if(nums.length==1){ result.add(nums[0]+""); } int pre = nums[0]; // previous element int first = pre; // first element of each range for(int i=1; i< nums.length; i++){ if(nums[i]==pre+1){ if(i==nums.length-1){ result.add(first+"->"+nums[i]); } }else{ if(first == pre){ result.add(first+""); }else{ result.add(first + "->"+pre); } if(i==nums.length-1){ result.add(nums[i]+""); } first = nums[i]; } pre = nums[i]; } return result; }