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"].

Solution


public class Solution {
    public List<String> findMissingRanges(int[] nums, int lower, int upper) {
        int last = lower - 1; // the last number
        List<String> ans = new ArrayList<String>();
        for(int num: nums) {
            // num is here
            // [last+1, num-1] need to be output
            if(num != last && num != last + 1) ans.add(outputRange(last+1,num-1));
            last = num;
        }
        if(last != upper) ans.add(outputRange(last+1, upper));
        return ans;
    }

    public String outputRange(int low, int high) {
        if(low == high) return ""+low;
        else return ""+low+"->"+high;
    }
}

results matching ""

    No results matching ""