228. Summary Ranges

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

Example 2:

Input:
 [0,2,3,4,6,8,9]

Output:
 ["0","2-
>
4","6","8-
>
9"]

Credits:
Special thanks to@jianchao.li.fighterfor adding this problem and creating all test cases.

class Solution {
    public List<String> summaryRanges(int[] nums) {
        List<String> ans = new ArrayList<>();
        if (nums == null || nums.length == 0) return ans;
        int start = nums[0], end = nums[0];

        for (int i = 1; i < nums.length; i++){
            if (nums[i] == end + 1){
                end = nums[i];
            }
            else if (nums[i] > end + 1){
                if (start == end){
                    ans.add(start + "");
                }
                else{
                    ans.add(start + "->" + end);
                }
                start = nums[i];
                end = nums[i];
            }
        }

        if (start == end){
            ans.add(start + "");
        }
        else{
            ans.add(start + "->" + end);
        }

        return ans;
    }
}

results for ""

    No results matching ""