[leetcode] 163. Missing Ranges 解题报告

题目链接: https://leetcode.com/problems/missing-ranges/

Given a sorted integer array where the range of elements are [lowerupper] inclusive, return its missing ranges.

For example, given [0, 1, 3, 50, 75]lower = 0 and upper = 99, return ["2", "4->49", "51->74", "76->99"].

思路: 为简化操作可以给原数组加一个新的上界, 比给定的多1, 然后维护一个区间, 初始区间的左端在lower的左边1, 右端为lower, 这样每次遍历一个元素先更新右边界, 如果左右边界相差2就往结果数组中添加一个数字, 如果相差多于2, 就添加一个区间, 然后更新左边界为当前元素.

代码如下:

class Solution {
public:
    vector<string> findMissingRanges(vector<int>& nums, int lower, int upper) {
        int left = lower-1, right = lower;
        vector<string> result;
        nums.push_back(upper+1);
        for(auto val: nums)
        {
            right = val;
            if(left+2 == right)
                result.push_back(to_string(left+1));
            else if(left+2 < right)
                result.push_back(to_string(left+1)+"->"+to_string(right-1));
            left = val;
        }
        return result;
    }
};


你可能感兴趣的:(LeetCode,array)