Simple java solution


  • 1
    H
    public List<String> summaryRanges(int[] nums) {
        List<String> res = new ArrayList<>();
        if (nums.length == 0) {return res;}
        if (nums.length == 1) {
            res.add(nums[0] + "");
            return res;
        }
        int p = 0;
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] == nums[i - 1] + 1) {
                if (i == nums.length - 1) {
                    res.add(nums[p] + "->" + nums[i]);
                }
            } else { 
                if (i == p + 1) {
                    res.add(nums[p] + "");
                } else {
                    res.add(nums[p] + "->" + nums[i - 1]);
                }
                if (i == nums.length - 1) {
                    res.add(nums[i] + "");
                }
                p = i;
            }
        }
        return res;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.