[Leetcode] Summary Ranges Summary Interval

Source: Internet
Author: User
Tags ranges

Given a sorted integer array without duplicates, return the summary of its ranges.

For example, given [0,1,2,4,5,7] , return["0->2","4->5","7"].

Credits:
Special thanks to @jianchao. Li.fighter for adding the problem and creating all test cases.

This question given us an ordered array, let us summarize the interval, specifically, let us find a continuous sequence, and then the first and last two numbers with a "-" to connect, then I just walk through the array, each check the next number is not incremented, if it is, then continue to traverse, if not, We also want to determine whether this is a number or a sequence, a number directly into the result, the sequence of words to be stored in the numbers and arrows "." We need two variables I and J, where I is the position of the starting digit of the sequential sequence, j is the length of the continuous series, and when J is 1 o'clock, it indicates that only one number, if greater than 1, is a sequential sequence with the following code:

classSolution { Public: Vector<string> Summaryranges (vector<int>&nums) {Vector<string>Res; inti =0, n =nums.size ();  while(I <N) {intj =1;  while(i + J < n && Nums[i + j]-nums[i] = = j) + +J; Res.push_back (J<=1? To_string (Nums[i]): to_string (Nums[i]) +" -"+ to_string (nums[i + J-1])); I+=J; }        returnRes; }};

Resources:

Https://leetcode.com/discuss/42204/7-13-lines-in-c

Https://leetcode.com/discuss/42298/9-lines-c-0ms-solution

[Leetcode] Summary Ranges Summary Interval

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.