java 163.缺少范围(#)。java

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 163.缺少范围(#)。java相关的知识,希望对你有一定的参考价值。

public class Solution {
    public List<String> findMissingRanges(int[] nums, int lower, int upper) {
        List<String> list = new ArrayList<String>();
        int preMiss = lower;
        for (int num : nums) {
            if (num == Integer.MAX_VALUE) {
                if (upper == num)
                    --upper;
                break;
            }
            preMiss = getNext(preMiss, num, list);
        }
        //handle anything not in the array that lower than the upper.
        if (preMiss == upper)
            list.add(preMiss + "");
        else if (preMiss < upper)
            list.add(preMiss + "->" + upper);
        return list;
    }

    private static int getNext(int miss, int num, List<String> list) {
        if (miss < num) {
            if (miss == num - 1)
                list.add(miss + "");
            else
                list.add(miss + "->" + (num - 1));
        }
        return num + 1;
    }
}
public class Solution {
    private String interval(int start, int end) {
        if (start == end) {
            return String.valueOf(start);
        }
        return start + "->" + end;
    }
    public List<String> findMissingRanges(int[] nums, int lower, int upper) {
        List<String> res = new ArrayList<>();
        if (nums == null || nums.length < 1) {
            res.add(interval(lower,upper));
            return res;
        } 
        int len = nums.length;
        if (lower - nums[0] != 0) {
            int start = lower;
            int end = nums[0] - 1;
            res.add(interval(start, end));
        }
        for (int i = 1; i < len; i++) {
            if (nums[i] == nums[i - 1]) continue; // [1,1,1]
            if (nums[i] != nums[i - 1] + 1) {
                int start = nums[i - 1] + 1;
                int end = nums[i] - 1;
                res.add(interval(start, end));
            }
        }
        if (upper - nums[len - 1] != 0) {
            int start = nums[len - 1] + 1;
            int end = upper;
            res.add(interval(start, end));
        }
        return res;
    }
}

以上是关于java 163.缺少范围(#)。java的主要内容,如果未能解决你的问题,请参考以下文章

java 163.缺少范围(#)。java

java 163.缺少范围(#)。java

java 163.缺少范围(#)。java

java 163.缺少范围(#)。java

算法笔记_163:算法提高 最大乘积(Java)

Java byte 类型的取值范围是-128~127