Easy Java 1ms solution with comments


  • 0
    D

    public class Solution {
    public List<String> summaryRanges(int[] nums) {

        //variable to store the answer
        List<String> answer=new ArrayList<String>();
        
        //Bases case: if 0 elements are present
        if(nums.length==0)
            return answer;
         
        //Base case: if 1 element is present   
        if(nums.length==1)
        {
            
            answer.add(Integer.toString(nums[0]));
            return answer;
        }
        
        
        //General case: if 2 or more numbers are present
        
        //pointers to keep track of the start and the end of the range
        int start_index=0;
        int end_index=-1;
        
        //String to keep track of the ranges
        String range="";
        
        //for loop to traverse through the array
        for(int i=1;i<nums.length;i++)
        {
            
            //to check if the elements are consecutive or not
            if(nums[i]-nums[i-1]!=1)
            {
                //update the end_index
                end_index=i-1;
                
                //check to see if they both point to the same element
                if(start_index==end_index)
                {
                    //add the lone element to the list
                    range=Integer.toString(nums[start_index]);
                }
                else
                {
                    range=Integer.toString(nums[start_index])+"->"+Integer.toString(nums[end_index]);
                    
                }
                
                answer.add(range);
                //update the value of start_index
                start_index=i;
            }
            else
                continue;
            
            
        }
        
        //update the end_index for the last value
        end_index=nums.length-1;
        
        //check to see if they point to the same element or not
        if(start_index==end_index)
        {
                    //add the lone element to the list
                    range=Integer.toString(nums[start_index]);
        }
        else
        {
                    range=Integer.toString(nums[start_index])+"->"+Integer.toString(nums[end_index]);
        }
        
        answer.add(range);
        //return the answer
        return answer;
    }
    

    }


Log in to reply
 

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