Monday, November 23, 2015

[leetcode]Missing Ranges

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class Solution {
    public List<String> findMissingRanges(int[] nums, int lower, int upper) {
        List<String> result = new ArrayList<String>();
        if (nums == null || nums.length == 0){
            result.add(generateString(lower, upper));
            return result;
        }
        int prev = lower-1;
        for (int i = 0; i < nums.length; i++){
            if (nums[i]-prev >= 2){
                result.add(generateString(prev+1, nums[i]-1));
            }
            prev = nums[i];
        }
        if (upper-nums[nums.length-1] > 0){
            result.add(generateString(nums[nums.length-1]+1,upper));
        }
        return result;
    }

    private String generateString(int from, int to){
        return from == to?""+from:from+"->"+to;
    }
}

No comments:

Post a Comment