Article directory
1. The topic
2. Ideas
Because there is a set boundary, firstly, lower-1 needs to be inserted into the front of nums (it can be directly in the vector insert
), and upper+1 is inserted into the end of nums (used here insert
or push_back
both). Then iterate over the array nums:
- If nums[i+1] - nums[i] = 1, the two adjacent numbers are already consecutive, so no processing is performed, i++
- If nums[i+1] - nums[i] = 2, add nums[i]+1
- If nums[i+1] - nums[i] > 2, add the interval nums[i]+1, nums[i+1]-1
summary:
- In fact, it is to determine the content of the answer array by traversing the
nums
array and comparing thenums[i]
sumnums[i+1]
. For example, according to thenums[3]=50
sumnums[4]=75
, the process of pushing51->74
character elements into the answer array is determined. - And the discussion is classified according to three situations.
to_string(a)
Convert a number to a string, different strings can be+
spliced, and note that single quotes are character types, and double quotes are string types.
3. Code
class Solution {
public:
vector<string> findMissingRanges(vector<int>& nums, int lower, int upper) {
vector<string>ans;
nums.insert(nums.begin(), lower - 1);
nums.push_back(upper + 1);
int size = nums.size();
for(int i = 0; i < size - 1; i++){
if(nums[i + 1] - nums[i] == 1){
continue;
}else if(nums[i + 1] - nums[i] == 2){
ans.push_back(to_string(nums[i] + 1));
}else{
//nums[i+1]-nums[i]>2时
ans.push_back(to_string(nums[i] + 1) + "->" + to_string(nums[i+1] - 1));
}
}
return ans;
}
};