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”]
模拟法。
General case就是从序号1开始,每次拿出nums[i - 1]和nums[i]就可以得到有效区间了,即[nums[i-1] + 1, nums[I] - 1]。然后头尾也加一下即可。具体加的形式可以写个分离的小函数来处理, private void addRange(List<String> ans, long start, long end)。
细节:
1.小函数的传参用long不用int。因为有那个+1,-1的部分,如果nums[i]本身已经是Integer.MIN_VALUE了,如果用int来传入一个nums[i]-1那传的数就错了,函数里对start end的大小对比逻辑也就不对了。
实现:
class Solution { public List<String> findMissingRanges(int[] nums, int lower, int upper) { List<String> ans = new ArrayList<>(); if (nums == null || nums.length == 0) { addRange(ans, lower, upper); return ans; } addRange(ans, lower, (long) nums[0] - 1); for (int i = 1; i < nums.length; i++) { addRange(ans, (long) nums[i - 1] + 1, (long)nums[i] - 1); } addRange(ans, (long) nums[nums.length - 1] + 1, upper); return ans; } private void addRange(List<String> ans, long start, long end) { if (start > end) { return; } else if (start == end) { ans.add(String.valueOf(start)); } else { ans.add(start + "->" + end); } } }