模拟
将 
    
     
      
       
        l
       
       
        o
       
       
        w
       
       
        e
       
       
        r
       
      
      
       lower
      
     
    lower 和 
    
     
      
       
        u
       
       
        p
       
       
        p
       
       
        e
       
       
        r
       
      
      
       upper
      
     
    upper 加入数组,避免边界判断。
 一次遍历,相邻元素差 
    
     
      
       
        1
       
      
      
       1
      
     
    1 ,无缺失;相邻元素差 
    
     
      
       
        2
       
      
      
       2
      
     
    2 ,缺失中间的一个数;相邻元素相差大于 
    
     
      
       
        2
       
      
      
       2
      
     
    2 ,缺失中间一段数。根据格式将数字转化字符串加入答案,即为所求。
class Solution {
public:
    vector<string> findMissingRanges(vector<int>& nums, int lower, int upper) {
        nums.insert(nums.begin(),lower-1);
        nums.push_back(upper+1);
        vector<string> ans;
        for(int i = 1;i<nums.size();i++)
            if(nums[i]-nums[i-1]==1) continue;
            else if(nums[i]-nums[i-1]==2) ans.push_back(to_string(nums[i]-1));
            else ans.push_back(to_string(nums[i-1]+1)+"->"+to_string(nums[i]-1));
        return ans;
    }
};
- 时间复杂度 : O ( n ) O(n) O(n) , n n n 是数字总数,一次遍历整数数组的时间复杂度 O ( n ) O(n) O(n) 。
- 空间复杂度 : O ( 1 ) O(1) O(1) , 除答案使用的空间外,没有使用额外的线性空间 。
AC

致语
- 理解思路很重要
- 读者有问题请留言,清墨看到就会回复的。



















