My java solution in detail


  • 3
    Z

    public class SummaryRanges {

    public List<String> summaryRanges(int nums[]){
    	
    	
        List<String> ranges = new ArrayList<String>(); //Initialize the return array
        
        if(nums.length == 0){ //If the array is empty, return directly
            return ranges;
        }
        
        if(nums.length == 1){ //If the array has a length of 1, just add to the return array
            ranges.add(String.valueOf(nums[0]));
        }
        
        int start = nums[0]; //Initialize an integer marker to mark the start of each range
        
        String pointer = "->";
        
        //Main logic goes here
        for(int i=0;i<=nums.length-2;i++){
            if(nums[i+1]-nums[i]!=1){       //Judge whether two adjacent integers are in same range
                if(nums[i] != start){       //If the start marker not equals to the number at current index,
                	                        //it means that this range has more than two elements
                  ranges.add(String.valueOf(start)+pointer+String.valueOf(nums[i]));
                }else{                      //Else, this range only contains one element.
                  ranges.add(String.valueOf(nums[i]));
                }
                if(i==nums.length-2){       //And we have to judge whether the next element is the last one element in array
                    ranges.add(String.valueOf(nums[i+1]));//If true, simply treat the last element as a new range and break from the loop
                    break;
                }
                start = nums[i+1];   //Otherwise, reset the start marker to the next element
            }else{
                if(i==nums.length-2){//If the last element is still within a range, end this loop by adding the last range to the return array
                    ranges.add(String.valueOf(start)+pointer+String.valueOf(nums[i+1]));
                    break;
                }
            }
        }
        
        return ranges;
    }
    

    }


Log in to reply
 

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