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