Missing Ranges
Given a sorted integer array where the range of elements are in the inclusive range [lower, upper], 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"].
直接上代码
1 public static List<String> findMissingRange(int[] arr, int lower, int upper) { 2 List<String> res = new ArrayList<>(); 3 int pre = lower - 1, after = 0; 4 for (int i = 0; i <= arr.length; i++) { 5 after = (i == arr.length ? upper + 1 : arr[i]); 6 if (pre + 2 == after) 7 res.add(String.valueOf(pre + 1)); 8 if (pre + 2 < after) 9 res.add(String.valueOf(pre + 1) + "->" + String.valueOf(after - 1)); 10 11 pre = after; 12 } 13 14 return res; 15 }