1ms Java solution


  • 0

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

        List<String> result = new ArrayList<>();
        if(nums.length == 0) return result;
        if(nums.length == 1) {
            result.add(nums[0]+"");
            return result;
        }
        
        int beginVal = nums[0];
        for(int i=1; i<nums.length; i++){
            if(nums[i]-nums[i-1] != 1){
                if(nums[i-1] > beginVal) result.add(beginVal+"->"+nums[i-1]);
                if(nums[i-1] == beginVal) result.add(beginVal+"");
                
                beginVal = nums[i];
            }
            
            if(i==nums.length-1) {
                if(nums[i]-nums[i-1] != 1) result.add(beginVal+"");
                if(nums[i]-nums[i-1] == 1) result.add(beginVal+"->"+nums[i]);
            }
        }
        return result;
    }
    

    }


Log in to reply
 

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