题目:
Given a sorted integer array where the range of elements are [lower, upper] inclusive, 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"].
链接: http://leetcode.com/problems/missing-ranges/
6/16/2017
1ms, 15%
最后一个testcase跑不过,一直以为是MAX_VALUE的边界值问题,后来才发现是重复元素问题。
注意:
1. 第15行,如果元素跟前面元素值相同,就不要做再一次更新lower了
2. 第19行及时退出,或者不要这个branch,直接在第7行改成 if(nums.length == 0 || lower > upper)。看来改在第7行是最好的,因为属于invalid输入
3. 第36行比较最后一个元素和upper
1 public class Solution { 2 public List<String> findMissingRanges(int[] nums, int lower, int upper) { 3 List<String> ret = new ArrayList<String>(); 4 if (nums == null) { 5 return ret; 6 } 7 if (nums.length == 0) { 8 addToResult(ret, lower, upper); 9 return ret; 10 } 11 for (int i = 0; i < nums.length; i++) { 12 if (lower > upper) { 13 return ret; 14 } 15 if (i != 0 && nums[i] == nums[i - 1]) { 16 continue; 17 } 18 if (nums[i] > lower) { 19 if (nums[i] > upper) { 20 addToResult(ret, lower, upper); 21 return ret; 22 } 23 addToResult(ret, lower, nums[i] - 1); 24 /* 25 if (nums[i] == Integer.MAX_VALUE) { 26 return ret; 27 } 28 */ 29 lower = nums[i] + 1; 30 } else { 31 /* 32 if (nums[i] == Integer.MAX_VALUE) { 33 return ret; 34 } 35 */ 36 lower += 1; 37 } 38 39 } 40 if (nums[nums.length - 1] < upper) { 41 addToResult(ret, lower, upper); 42 } 43 return ret; 44 } 45 private void addToResult(List<String> ret, int lower, int upper) { 46 if (lower == upper) { 47 ret.add(Integer.toString(lower)); 48 } else { 49 ret.add(Integer.toString(lower) + "->" + Integer.toString(upper)); 50 } 51 return; 52 } 53 }
很多解法都是以前提交的,这个新的解决了很多test case的问题
https://discuss.leetcode.com/topic/75188/accepted-java-solution-8-lines-0ms
1 public class Solution { 2 public List<String> findMissingRanges(int[] nums, int lower, int upper) { 3 List<String> res = new ArrayList<>(); 4 for(int i : nums) { 5 if(i > lower) res.add(lower+((i-1 > lower)?"->"+(i-1):"")); 6 if(i == upper) return res; // Avoid overflow 7 lower = i+1; 8 } 9 if(lower <= upper) res.add(lower + ((upper > lower)?"->"+(upper):"")); 10 return res; 11 } 12 }
更多讨论
https://discuss.leetcode.com/category/171/missing-ranges
时间: 2024-08-03 14:16:13