Missing Ranges 解答
Posted 树獭君要好好学算法
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Missing Ranges 解答相关的知识,希望对你有一定的参考价值。
Question
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"].
Answer
遍历数组,如果arr[i] > arr[i-1] + 1则说明arr[i]与arr[i-1]中有missing range。注意考虑开头和结尾。
1 public 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 addRange(result, lower, upper); 6 return result; 7 } 8 int len = nums.length; 9 // process head 10 if (nums[0] > lower) { 11 addRange(result, lower, nums[0] - 1); 12 } 13 for (int i = 1; i < len; i++) { 14 if (nums[i] > nums[i - 1] + 1) { 15 addRange(result, nums[i - 1] + 1, nums[i] - 1); 16 } 17 } 18 // process tail 19 if (nums[len - 1] < upper) { 20 addRange(result, nums[len - 1] + 1, upper); 21 } 22 return result; 23 } 24 25 private void addRange(List<String> result, int low, int high) { 26 StringBuilder sb = new StringBuilder(); 27 sb.append(low); 28 if (high > low) { 29 sb.append("->"); 30 sb.append(high); 31 } 32 result.add(sb.toString()); 33 } 34 }
以上是关于Missing Ranges 解答的主要内容,如果未能解决你的问题,请参考以下文章