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"].
这种题就是要写的clean and tidy,好方法:
1 public class Solution { 2 public List<String> summaryRanges(int[] nums) { 3 List<String> res = new ArrayList<String>(); 4 if (nums==null || nums.length==0) return res; 5 for (int i=0; i<nums.length; i++) { 6 int temp = nums[i]; 7 while (i+1<nums.length && nums[i+1]==nums[i]+1) i++; 8 if (temp == nums[i]) { 9 res.add(temp+""); 10 } 11 else { 12 res.add(temp+"->"+nums[i]); 13 } 14 } 15 return res; 16 } 17 }
维护两个指针的方法:
1 public class Solution { 2 public List<String> summaryRanges(int[] nums) { 3 List<String> res = new ArrayList<String>(); 4 if (nums == null || nums.length == 0) return res; 5 int l= 0, r = 0; 6 for (r=0; r<nums.length-1; r++) { 7 if (nums[r] != nums[r+1]-1) { 8 if (nums[r] == nums[l]) res.add(nums[l] + ""); 9 else res.add(nums[l] + "->" + nums[r]); 10 l = r+1; 11 } 12 } 13 if (nums[r] == nums[l]) res.add(nums[l] + ""); 14 else res.add(nums[l] + "->" + nums[r]); 15 return res; 16 } 17 }