163. Missing Ranges
题目:
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/
题解:
查找丢失的range。这道题目主要注意一些边界条件。数组为空时要加入lower或者lower -> upper。不为空时可以先做一个特殊处理lower--,这样可以在变例数组的时候用条件getRangeAsString(lower + 1,nums[i] - 1)来把lower包括进来。遍历完毕数组之后要比较此时的lower以及upper,再尝试update list。
Time Complexity - O(n), Space Complexity - O(n)。
public class Solution { public List<String> findMissingRanges(int[] nums, int lower, int upper) { List<String> res = new ArrayList<>(); if(nums == null) return res; if(nums.length == 0) { res.add(getRangeAsString(lower, upper)); return res; } lower--; //to include lower; for(int i = 0; i < nums.length; i++) { if(nums[i] - lower >= 2) // lower always <= nums[i] res.add(getRangeAsString(lower + 1, nums[i] - 1)); lower = nums[i]; } if(upper > lower) // boundary condition, include upper res.add(getRangeAsString(lower + 1, upper)); return res; } private String getRangeAsString(int lower, int upper) { if(lower == upper) return String.valueOf(lower); StringBuilder sb = new StringBuilder(); sb.append(lower); sb.append("->"); sb.append(upper); return sb.toString(); } }
二刷:
方法跟一刷一样,但更新了一下边界条件的写法。也是建立了一个辅助方法来返回单个字符或者一个range。 遍历数组的时候,每次当num - lower >= 1时,我们进行结果集的添加操作,然后更新lower = num + 1。遍历完毕以后要再check一下 lower 和 upper的关系。
Java:
Time Complexity - O(n), Space Complexity - O(n)。
public class Solution { public List<String> findMissingRanges(int[] nums, int lower, int upper) { List<String> res = new ArrayList<>(); if (nums == null || lower > upper) return res; for (int num : nums) { if (num - lower >= 1) res.add(getRangeString(lower, num - 1)); lower = num + 1; } if (lower <= upper) res.add(getRangeString(lower, upper)); return res; } private String getRangeString(int lower, int upper) { if (lower == upper) return String.valueOf(lower); StringBuilder sb = new StringBuilder(); sb.append(lower).append("->").append(upper); return sb.toString(); } }
测试: