Leetcode-Missing Ranges
Given a sorted integer array where the range of elements are [lower, upper] inclusive, return its missing ranges.
For example, given [0, 1, 3, 50, 75]
, lower = 0 and upper = 99, return ["2", "4->49", "51->74", "76->99"].
A better solution:
public class Solution { public List<String> findMissingRanges(int[] nums, int lower, int upper) { List<String> resList = new LinkedList<String>(); if (nums.length==0){ addRange(resList,lower,upper); return resList; } int first = -1; for (int i=0;i<nums.length;i++) if (nums[i]>=lower){ first = i; break; } int start = nums[first], end = nums[first]; addRange(resList,lower,start-1); for (int i=first+1;i<nums.length;i++){ if (nums[i]>upper) break; if (nums[i]==end+1){ end = nums[i]; } else { addRange(resList,end+1,nums[i]-1); start = nums[i]; end = nums[i]; } } addRange(resList,end+1,upper); return resList; } public void addRange(List<String> resList, int lower, int upper){ if (upper < lower) return; if (lower==upper) resList.add(Integer.toString(lower)); else resList.add(Integer.toString(lower)+"->"+Integer.toString(upper)); } }
Solution:
1 public class Solution { 2 public List<String> findMissingRanges(int[] A, int lower, int upper) { 3 //for a range lower-upper, and a number A[i], we have conditions: 4 //1. A[i]<lower: move to i+1; 5 //2. A[i]==lower: lower -> A[i]+1 6 //3. lower<A[i]<=upper: generate a range: lower->A[i]-1; lower becomes A[i]+1. NOTE A[i]==upper: end of the program. 7 //4. A[i]>upper: get range: lower->upper, end of the problem. 8 9 List<String> res = new ArrayList<String>(); 10 11 for (int i=0;i<A.length;i++){ 12 if (A[i]<lower) continue; 13 14 if (A[i]==lower){ 15 lower=A[i]+1; 16 continue; 17 } 18 19 if (A[i]>lower && A[i]<=upper){ 20 String range = ""; 21 if (lower!=A[i]-1) range = Integer.toString(lower)+"->"+Integer.toString(A[i]-1); 22 else range = Integer.toString(lower); 23 res.add(range); 24 lower = A[i]+1; 25 if (A[i]==upper) break; 26 else continue; 27 } 28 29 if (A[i]>upper){ 30 String range = ""; 31 if (lower!=upper) range = Integer.toString(lower)+"->"+Integer.toString(upper); 32 else range = Integer.toString(lower); 33 res.add(range); 34 lower = A[i]+1; 35 break; 36 } 37 } 38 39 if (lower<=upper){ 40 String range = ""; 41 if (lower!=upper) range = Integer.toString(lower)+"->"+Integer.toString(upper); 42 else range = Integer.toString(lower); 43 res.add(range); 44 } 45 46 return res; 47 } 48 }