[LeetCode 228] Summary Ranges (Medium)

Given a sorted integer array without duplicates, return the summary of its ranges.

Example 1:

Input:  [0,1,2,4,5,7]
Output: ["0->2","4->5","7"]
Explanation: 0,1,2 form a continuous range; 4,5 form a continuous range.

Example 2:

Input:  [0,2,3,4,6,8,9]
Output: ["0","2->4","6","8->9"]
Explanation: 2,3,4 form a continuous range; 8,9 form a continuous range.

Code

class Solution {
    public List summaryRanges(int[] nums) {
        List result = new ArrayList<> ();
        if (nums == null || nums.length == 0)
            return result;
        
        List range = new ArrayList<> ();
        int start = nums[0];
        double end = Double.MAX_VALUE;
       
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] == nums[i - 1] + 1) {
                end = nums[i];
                continue;
            }
            
            String endRange = end == Double.MAX_VALUE ? "" : "->" + (int) (end);
            String entry = String.valueOf (start) + endRange;
            range.add (entry);
            
            start = nums[i];
            end = Double.MAX_VALUE;
        }
        
        String endRange = end == Double.MAX_VALUE ? "" : "->" + (int)end;
        String entry = String.valueOf (start) + endRange;
        range.add (entry);
        
        return range;
    }
}

你可能感兴趣的:([LeetCode 228] Summary Ranges (Medium))