[Leetcode 163] Missing Ranges

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     }

 

上一篇:【CodeForces-1041C】Coffee Break(二分解决关于set,pair,upper_bound用法)


下一篇:LeetCode 34 - 在排序数组中查找元素的第一个和最后一个位置 - [二分][lower_bound和upper_bound]