2015年11月3日星期二

Leetcode 228 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"].
Solution 1: simple looping
 public class Solution {  
   public List<String> summaryRanges(int[] nums) {  
     List<String> res=new ArrayList<>();  
     int i=0, n=nums.length;  
     for (int j=0; j<n; j++) {  
       if (j==n-1 || nums[j]+1!=nums[j+1]) {  
         if (i==j) res.add(String.valueOf(nums[j]));  
         else res.add(String.valueOf(nums[i])+"->"+String.valueOf(nums[j]));  
         i=j+1;  
       }  
     }  
     return res;  
   }  
 }  

没有评论:

发表评论