标签:style blog io ar color os sp for on
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"].
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 }
标签:style blog io ar color os sp for on
原文地址:http://www.cnblogs.com/lishiblog/p/4160849.html