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

For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"].

Solution

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

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

        return ans;   
    }
}

results matching ""

    No results matching ""