Make writing a habit together! This is the 9th day of my participation in the “Gold Digging Day New Plan · April More text Challenge”. Click here for more details.
Topic describes
Original link:
228. Summary interval
Given an ordered array of integers with no repeating elements, nums.
Returns a list of minimum ordered ranges that cover exactly all the numbers in the array. That is, every element of NUMS is covered by exactly some range, and there is no number X that belongs to a range but is not numS.
Each interval range [a,b] in the list should be printed in the following format:
- “A -> B”, if A! = b
- “A”, if a is equal to b
Example 1:
Input: nums =,1,2,4,5,7 [0] output: [" 0 - > 2 ", "4 - > 5", "7"] to explain: the range is: [0, 2] -- > "0 - > 2" (4, 5) - > "4 - > 5 [7, 7]" - > "7"Copy the code
Example 2:
Input: nums =,2,3,4,6,8,9 [0] output: [" 0 ", "2 - > 4", "6", 8 - > "9"] : range is: [0, 0] - > "0" (2, 4] - > 2 - > 4 "[6] - > [8, 9]" 6 "- >" 8 - > 9"Copy the code
Tip:
- 0 <= nums.length <= 20
- -2^31 <= nums[i] <= 2^31 – 1
- All values in NUMS are different
- Nums are arranged in ascending order
Thought analysis
Nums [j]+1! Nums [j]+1! = nums[j+1], insert string from I to j, after insertion, move I to the position after j, that is, I = j+1.
If the array is empty or there is only one element, the loop statement is also difficult to determine, because it cannot be compared with the second element. Some critics use the skip method, that is, insert an extra integer maximum after the array, but this method will result in error if the array originally the last element is a maximum of -1.
AC code
vector<string> summaryRanges(vector<int> &nums) {
vector<string> s;
if (nums.size() == 0)
return s;
if (nums.size() == 1) {
s.push_back(to_string(nums[0]));
return s;
}
int i = 0, j = 0, n = nums.size();
string t;
for (; j < n - 1; j++) {
if (nums[j] + 1! = nums[j +1]) {
if (i == j)
s.push_back(to_string(nums[i]));
else
s.push_back(to_string(nums[i]) + "- >" + to_string(nums[j]));
i = j + 1; }}if (i == j)
s.push_back(to_string(nums[i]));
else
s.push_back(to_string(nums[i]) + "- >" + to_string(nums[j]));
return s;
}
Copy the code