Given a sorted integer array where the range of elements are in the inclusive range [lower, upper], return its missing ranges.
Given nums = [0, 1, 3, 50, 75], lower = 0 and upper = 99
return ["2", "4->49", "51->74", "76->99"].
The algorithm to solve this problem is pretty straightforward. The hard part is to think of all cases and handle them correctly.
All possible corner cases are shown as follows.
1. nums has no elements;
2. the first element is bigger than lower
3. the last element is smaller than upper
Another place that needs our attention is when subtracting two numbers to get the difference. Because the elements in nums,
lower and upper can be very big or very small, so the subtraction operation to get the diff can overflow the integer size, causing
incorrect behavior when using diff's value to determine what to do.
For example, if nums[0] = 1, lower = Integer.MIN_VALUE, then nums[0] - lower > Integer.MAX_VALUE, OVERFLOW!!!
As a result, we initialize diff as type of long, and convert all operands to long in these diff subtractions.
1 public class Solution { 2 /** 3 * @param nums a sorted integer array 4 * @param lower an integer 5 * @param upper an integer 6 * @return a list of its missing ranges 7 */ 8 public List<String> findMissingRanges(int[] nums, int lower, int upper) { 9 List<String> missRange = new ArrayList<String>(); 10 if(nums == null){ 11 return missRange; 12 } 13 if(nums.length == 0){ 14 if(lower == upper){ 15 missRange.add(String.valueOf(lower)); 16 } 17 else{ 18 missRange.add(String.valueOf(lower) + "->" + String.valueOf(upper)); 19 } 20 return missRange; 21 } 22 int n = nums.length; 23 long diff = 0; 24 if(nums[0] > lower){ 25 diff = (long)nums[0] - (long)lower; 26 if(diff == 1){ 27 missRange.add(String.valueOf(lower)); 28 } 29 else{ 30 missRange.add(String.valueOf(lower) + "->" + String.valueOf(nums[0] - 1)); 31 } 32 } 33 for(int i = 1; i < n; i++){ 34 diff = (long)nums[i] - (long)nums[i - 1]; 35 if(diff > 0){ 36 if(diff == 2){ 37 missRange.add(String.valueOf(nums[i - 1] + 1)); 38 } 39 else if(diff > 2){ 40 missRange.add(String.valueOf(nums[i - 1] + 1) + "->" + String.valueOf(nums[i] - 1)); 41 } 42 } 43 } 44 if(nums[n - 1] < upper){ 45 diff = (long)upper - (long)nums[n - 1]; 46 if(diff == 1){ 47 missRange.add(String.valueOf(upper)); 48 } 49 else{ 50 missRange.add(String.valueOf(nums[n - 1] + 1) + "->" + String.valueOf(upper)); 51 } 52 } 53 return missRange; 54 } 55 }
本文介绍了一种用于查找给定排序整数数组中缺失区间的算法。该算法考虑了多种特殊情况,如数组为空、首元素大于指定下限或末元素小于上限等。同时,为了避免整数溢出问题,采用了长整型进行数值计算。
384

被折叠的 条评论
为什么被折叠?



