163. Missing Ranges & Summary Ranges
Missing Ranges
You are given an inclusive range [lower, upper] and a sorted unique integer array nums, where all elements are in the inclusive range.
A number x is considered missing if x is in the range [lower, upper] and x is not in nums.
Return the smallest sorted list of ranges that cover every missing number exactly. That is, no element of nums is in any of the ranges, and each missing number is in one of the ranges.
Each range [a,b] in the list should be output as:
"a->b"ifa != b"a"ifa == b
Example 1:
Input: nums = [0,1,3,50,75], lower = 0, upper = 99 Output: ["2","4->49","51->74","76->99"] Explanation: The ranges are: [2,2] --> "2" [4,49] --> "4->49" [51,74] --> "51->74" [76,99] --> "76->99"
Example 2:
Input: nums = [], lower = 1, upper = 1 Output: ["1"] Explanation: The only missing range is [1,1], which becomes "1".
Example 3:
Input: nums = [], lower = -3, upper = -1 Output: ["-3->-1"] Explanation: The only missing range is [-3,-1], which becomes "-3->-1".
Example 4:
Input: nums = [-1], lower = -1, upper = -1 Output: [] Explanation: There are no missing ranges since there are no missing numbers.
Example 5:
Input: nums = [-1], lower = -2, upper = -1 Output: ["-2"]
1 class Solution { 2 public List<String> findMissingRanges(int[] nums, int lower, int upper) { 3 List<String> result = new ArrayList<>(); 4 if (nums == null || nums.length == 0) { 5 result.add(formRange(lower, upper)); 6 return result; 7 } 8 9 // 1st step 10 if (nums[0] > lower) { 11 result.add(formRange(lower, nums[0] - 1)); 12 } 13 14 // 2nd step 15 for (int i = 0; i < nums.length - 1; i++) { 16 if (nums[i + 1] > nums[i] + 1) { 17 result.add(formRange(nums[i] + 1, nums[i + 1] - 1)); 18 } 19 } 20 21 // 3rd step 22 if (nums[nums.length - 1] < upper) { 23 result.add(formRange(nums[nums.length - 1] + 1, upper)); 24 } 25 return result; 26 } 27 28 public String formRange(int low, int high) { 29 return low == high ? String.valueOf(low) : (low + "->" + high); 30 } 31 }
Summary Ranges
Given a sorted integer array without duplicates, return the summary of its ranges.
For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"].
1 public class Solution { 2 public List<String> summaryRanges(int[] nums) { 3 List<String> list = new ArrayList<>(); 4 if (nums == null || nums.length == 0) return list; 5 6 int start = 0, i = 1; 7 for (; i < nums.length; i++) { 8 if (nums[i] != nums[i - 1] + 1) { 9 list.add(formRange(nums[start], nums[i - 1])); 10 start = i; 11 } 12 } 13 14 list.add(formRange(nums[start], nums[nums.length - 1])); 15 return list; 16 } 17 18 public String formRange(int low, int high) { 19 return low == high ? String.valueOf(low) : (low + "->" + high); 20 } 21 }

浙公网安备 33010602011771号