[LeetCode163] Missing interval (to_string)

Article directory

1. The topic

insert image description here

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 insertor push_backboth). 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 numsarray and comparing the nums[i]sum nums[i+1]. For example, according to the nums[3]=50sum nums[4]=75, the process of pushing 51->74character 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;
    }
};

Guess you like

Origin blog.csdn.net/qq_35812205/article/details/123838279