163. Missing Ranges

Given a sorted integer array where the range of elements are in the inclusive range [lower, upper], 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"].

一刷
题解:如果当前值与lower相等,那么lower和i都要自加,找到下一个缺失的。比如lower=1, nums = {1,2,3}, 缺失的为4

public class Solution {
    public List<String> findMissingRanges(int[] nums, int lower, int upper) {
        List<String> res = new ArrayList<>();
        if(nums.length==0){
            res.add(getRange(lower, upper));
            return res;
        }
        
        int next = lower;
        
        for(int i=0; i<nums.length; i++){
            if(nums[i]<next) continue;
            if(i+1<nums.length && nums[i] == nums[i+1]) continue;
            if(nums[i] == next){//increase the lower, the next was missed
                next++;
                continue;
            }
            res.add(getRange(next, nums[i]-1));
            
            next = nums[i]+1;
        }
        if(next == Integer.MIN_VALUE && upper==Integer.MAX_VALUE) return res;
        if(next<=upper) res.add(getRange(next, upper));
        
        return res;
        
    }
    
    private String getRange(int a, int b){
        if(a == b) return String.valueOf(a);
        else return String.format("%d->%d", a, b);
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容