Missing Ranges

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

思路:这是我见到的最简单的版本,用start和end来表示区间,刚开始start = lower,最后end用upper,中间start = num+1, end = num - 1;

注意用long来防止溢出,比如Integer.MAX_VALUE + 1会变成负数,直接转换成long就可以防止溢出了;

class Solution {
    public List findMissingRanges(int[] nums, int lower, int upper) {
        List list = new ArrayList();
        long start = lower;
        // 直接把num转换成long,防止溢出;
        for(long num : nums) {
            long end = num - 1;
            addRange(list, start, end);
            start = num + 1;
        }
        addRange(list, start, upper);
        return list;
    }
    
    private void addRange(List list, long start, long end) {
        if(start == end) {
            list.add(String.valueOf(start));
        } else if(start < end) {
            list.add(String.valueOf(start) + "->" + String.valueOf(end));
        }
    }
}

 

 

 

你可能感兴趣的:(Array)