Given a sorted integer array nums, where the range of elements are in the inclusive range [lower, upper], return its missing ranges.
Example:
Input: nums = [0, 1, 3, 50, 75], lower = 0 and upper = 99,
Output: ["2", "4->49", "51->74", "76->99"]
题意:
给定一个区间和一堆数。统计一下在此区间有哪些数没在数组中出现,结果用区间表示。
思路:
这题跟[leetcode]228. Summary Ranges区间统计思路一致
区别是因为规定了 [lower, upper] 要考虑更多的边界
代码:
1 class Solution { 2 public List<String> findMissingRanges(int[] a, int lower, int upper) { 3 List<String> result = new ArrayList<>(); 4 5 if(a.length == 0) { 6 group(result, lower, upper ); 7 return result; 8 } 9 10 if(a[0] != lower){ 11 group(result, lower, a[0] - 1); 12 } 13 14 for(int i = 1; i < a.length; i++ ){ 15 if( a[i] != a[i-1] && a[i] != a[i-1] + 1){ 16 group(result, a[i-1] + 1, a[i] - 1 ); 17 } 18 } 19 20 if(upper != a[a.length - 1] ){ 21 group(result, a[a.length - 1] + 1 , upper); 22 } 23 return result; 24 } 25 26 private void group(List<String> list, int start, int end){ 27 if(start == end ){ 28 list.add(start +""); 29 }else{ 30 list.add(start + "->" + end ); 31 } 32 } 33 }