Wednesday, November 25, 2015

[leetcode]Summary Range

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
public class Solution {
    public List<String> summaryRanges(int[] nums) {
        List<String> result = new ArrayList<String>();
        if (nums == null || nums.length == 0) return result;
        int prev = 0;
        int current = 1;
        while (current < nums.length){
            if (nums[current] != nums[current-1]+1){
                result.add(generateRange(nums[prev], nums[current-1]));
                prev = current;
            }
            current++;
        }
        result.add(generateRange(nums[prev], nums[current-1]));
        return result;
    }

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

No comments:

Post a Comment