163.缺失的空间

给定一个排序的整数数组 nums ,其中元素的范围在 闭区间 [lower, upper] 当中,返回不包含在数组中的缺失区间。

示例:

输入: nums = [0, 1, 3, 50, 75], lower = 0 和 upper = 99,
输出: ["2", "4->49", "51->74", "76->99"]

#include <vector>
 #include <string>
class Solution {
public:
    vector<string> findMissingRanges(vector<int>& nums, int lower, int upper) {
        vector<string> vec;
        string str="";
        //nums数组为空时,对应lower==upper和lower!=upper两种情况
        if(nums.size()==0){
            if(lower==upper) {str+=to_string(lower); vec.push_back(str); return vec;}
            str+=to_string(lower);
            str+='-';
            str+='>';
            str+=to_string(upper);
            vec.push_back(str);
            return vec;
        }
        //处理一下lower和nums[0]之间关系
        if(nums[0]!=lower) {
            if(nums[0]-1==lower) {
                str+=(to_string(lower));
                vec.push_back(str);
            }
            else {
                str+=(to_string(lower));
                str+='-';
                str+='>';
                str+=(to_string(nums[0]-1));
                vec.push_back(str);
            }
        }
        //处理nums[1]到nums[nums.size()-1]之间的关系
        for(int i=1;i<nums.size();i++){
            str="";
            if(nums[i]-nums[i-1]==1) continue;
            if(nums[i]-nums[i-1]==2) {
                str+=to_string(nums[i]-1);
                vec.push_back(str);
            }
            else{
                str+=to_string(nums[i-1]+1);
                str+='-';
                str+='>';
                str+=to_string(nums[i]-1);
                vec.push_back(str);
            }
        }
        //处理nums[nums.size()-1]到upper之间关系
        if(nums[nums.size()-1]!=upper){
            str="";
            if(nums[nums.size()-1]+1==upper) {
                str+=to_string(upper);
                vec.push_back(str);
            }
            else{
                str+=to_string(nums[nums.size()-1]+1);
                str+='-';
                str+='>';
                str+=to_string(upper);
                vec.push_back(str);
            }
        }
        return vec;
    }
};

  

class Solution:
    def findMissingRanges(self, nums: List[int], lower: int, upper: int) -> List[str]:
        vec = []
        low = lower - 1
        nums.append(upper+1)
        for num in nums:
            dis = num - low
            if dis == 2: vec.append(str(low + 1))
            elif dis > 2: vec.append(str(low + 1) + "->" + str(num - 1))
            low = num
        return vec

  

posted @ 2022-12-29 19:30  yyer  阅读(26)  评论(0编辑  收藏  举报