Accepted Solution: Java


  • 0
    D

    Logic: Keep a track of the first element in the range in the variable min. Traverse the array and find the end of the range (nums[i+1] != nums[i]). Add the range into the ArrayList in the form of min->last if min != last, or else "last" if min == last (only one element in this range). Update the min to the next element depending upon whether the element if last element or not.

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

        List<String> range = new ArrayList<String>();
        
        int min = nums[0];
        
        for(int i = 0; i < nums.length; i++){
            if(i == nums.length - 1 || nums[i+1] != nums[i] + 1){
                if(min != nums[i])
                    range.add(min + "->" + nums[i]);
                else
                    range.add(Integer.toString(nums[i]));
                if(i < nums.length - 1)
                    min = nums[i+1];
            }
        }
    
        return range;
    }
    

    }
    '''


Log in to reply
 

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