#leetcode #missing Ranges

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.