Given a sorted integer array where the range of elements are [0, 99] inclusive, return its missing ranges. For example, given [0, 1, 3, 50, 75], return [“2”, “4->49”, “51->74”, “76->99”]
You should be able to extend the above cases not only for the range [0,99], but any arbitrary range [start, end].
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
publicclass Solution{ public List<String> getMissingRanges(int[] nums, int start, int end){ List<String> ranges = new ArrayList<>(); int prev = start - 1; for(int i = 0; i <= nums.length; i++){ int curr = (i == nums.length) ? end + 1 : nums[i]; if(curr - prev >= 2){ ranges.add(getRange(prev + 1, curr - 1)); } prev = curr; } return ranges; } private String (int from, int to){ return from == to ? String.valueOf(from) : from + "->" + to; } }
近期评论