Missing Ranges
Given a sorted integer array where the range of elements is [lower, upper] inclusive, return its missing ranges.
For example, given [0, 1, 3, 2,--], lower = 0 and upper =, return ["", "4->49", "51->74", "76->99"].
Iterate through the array elements, removing the gaps. Notice the situation on both sides.
classSolution { Public: Vector<string> Findmissingranges (intA[],intNintLowerintUpper) {Vector<string>ret; if(n = =0) returnret; stringstr; if(Lower < a[0]) { if(Lower < a[0]-1) Str= To_string ((Long Long) lower) +" -"+ To_string ((Long Long) a[0]-1); Else //lower = = A[0]-1str = to_string (Long Long) lower); Ret.push_back (str); } for(inti =1; I < n; i + +) { if(A[i]-a[i-1] <2) Continue; if(A[i]-a[i-1] >2) Str= To_string ((Long Long) a[i-1]+1) +" -"+ To_string ((Long Long) a[i]-1); Else //A[i]-a[i-1] = = 2str = to_string (Long Long) a[i-1]+1); Ret.push_back (str); } if(a[n-1] <Upper) { if(a[n-1] < upper-1) Str= To_string ((Long Long) a[n-1]+1) +" -"+ To_string ((Long Long) Upper); Else //Upper = = A[n-1]+1str = to_string (Long Long) Upper); Ret.push_back (str); } returnret; }};
Here are my test cases, all through:
voidDisplay (vector<string>&ret) { for(inti =0; I < ret.size (); i + +) {cout<< Ret[i] <<" "; } cout<<Endl;}intMain () {solution S; inta[1]; //expect: ["0->9"]vector<string> ret = s.findmissingranges (A,0,0,9); Display (ret); intb[1] = {6}; //expect: ["0->5", "7->9"]ret = S.findmissingranges (B,1,0,9); Display (ret); intc[3] = {0,1,2}; //expect: []ret = S.findmissingranges (C,3,0,2); Display (ret); intd[5] = {0,1,3, -, the}; //expect: ["2", "4->49", "51->74", "76->99"]ret = S.findmissingranges (D,5,0, About); Display (ret);}
"Leetcode" Missing Ranges