Missing RangesTotal Accepted: 2544 Total Submissions: 10515 My SubmissionsQuestionSolution
Given a sorted integer array where the range of elements is [lower, Upper] inclusive, return its missin G Ranges.
For example, given [0, 1, 3, 50, 75] , lower = 0 and upper =, return["2", "4->49", "51->74", "76->99"].
The first idea of the problem is from lower to upper cycle, see which section in the given array is not, so there is a disadvantage, that is, if the lower ~ Upper range is very large, it is not efficient, so the input array loop, maintain a current m Issing the starting value of range x, if x = = Nums "I", X + +, I + +, if x > nums[i], skip, if x < nums[i], then need to put [X, Nums[i]-1 ] This missing range is added to result set, and after the end of the loop it is also determined if missing range exists between upper and X.
Need to understand the idea of cyclic invariant, there is a trap is when nums.length = = 0, do not return to the empty value as usual, here [lower, Upper] are all missing Range.
public class Solution {public list<string> findmissingranges (int[] nums, int lower, int upper) {list< string> res = new arraylist<string> (); if (nums = = null) return res; if (Nums.length = = 0) {res.add (GetRange (lower, upper)); return res; } int low = lower; for (int i = 0; i < nums.length; i++) {if (Nums[i] < low) {continue; }else if (nums[i] = = low) {low++; }else{//Nums[i] > Low, then we should add range Low ~ nums[i]-1 to result set Res.add (GetRange (Low, Nums[i]-1)); Low = Nums[i] + 1; }} if (upper >= low) {Res.add (GetRange (Low, upper)); } return res; Private String getRange (int min, int max) {if (min = = max) {return string.valueof (min); }else{return string.valueof (min) + "+" + STring.valueof (max); } }}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
#leetcode #missing Ranges