Java simple code, 1 for loop, with explanation


  • 0

    We loop once through the array, stop and add to the list if we see a jump (difference between 2 adjacent elements is greater than 1) or it reaches the end of the array. We decide to add "->" if the last element in the string to be added is greater than the start element in the same string to be added.

    public List<String> summaryRanges(int[] nums) {
        List<String> R = new ArrayList();
        if (nums.length==0) return R;
        String s = Integer.toString(nums[0]);
        int start = nums[0];
        for (int i=0; i<nums.length; i++)
            if (i==nums.length-1 || (i!=nums.length-1 && nums[i+1]>nums[i]+1)) {
                if (nums[i]>start) s += "->" + nums[i];
                R.add(s);
                if (i!=nums.length-1) {
                    start = nums[i+1];
                    s = Integer.toString(nums[i+1]);
                }
            }
        return R;
    }

Log in to reply
 

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