Sunday, September 17, 2017

228. Summary Ranges

Given a sorted integer array without duplicates, return the summary of its ranges.
Example 1:
Input: [0,1,2,4,5,7]
Output: ["0->2","4->5","7"]
Example 2:
Input: [0,2,3,4,6,8,9]
Output: ["0","2->4","6","8->9"]
Solution:
Since it is sorted, we can simply check if current continuous range is over by checking the current element - previous element. Obviously, if it is in the continuous range, the current should be the next integer of previous element which should be always is larger than previous one by 1.
Also,we can check if the range has only one element by checking the index difference in this range.

   public List<String> summaryRanges(int[] nums) {  
     List<String> res=new ArrayList<String>();  
     if(nums==null || nums.length==0) return res;  
     int pre=0;  
     for(int i=1;i<=nums.length;i++){  
       if(i==nums.length || nums[i]-nums[i-1]!=1){  
         StringBuilder sb=new StringBuilder();  
         sb.append(nums[pre]);  
         if(i-1!=pre){  
           sb.append("->");  
           sb.append(nums[i-1]);  
         }  
         res.add(sb.toString());  
         pre=i;  
       }  
     }  
     return res;  
   }  

No comments:

Post a Comment