My Easy to Understand Java 1ms Clean Solution (Used a Helper Function for String Output)


  • 0
    public List<String> summaryRanges(int[] nums) {
        List<String> range = new ArrayList<>();
        if (nums.length <= 1) {
            if (nums.length == 1)   range.add(getRange(nums[0], nums[0]));
            return range;
        }
        int i = 0, j = 0;
        while (i < nums.length) {
            while (j+1 < nums.length && nums[j+1]-1 == nums[j])   j++;
            range.add(getRange(nums[i], nums[j]));
            i = ++j;
        }
        return range;
    }
    
    private String getRange(int from, int to) {
        return from == to ? String.valueOf(from) : from + "->" + to;
    }
    

Log in to reply
 

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