Java clean and easy solution


  • 0
    D
    public List<String> summaryRanges(int[] nums) {
        List<String> result = new ArrayList<String>();
        int pre = 0;
        for(int i = 0; i < nums.length; i++){
            pre = i;
            while(i < nums.length - 1 && nums[i] == nums[i + 1] - 1){
                i++;
            }
            String str = getRange(nums, pre, i);
            result.add(str);
        }
        return result;
    }
    
    private String getRange(int[] nums, int start, int end){
        if(start == end){
            return nums[start] + "";
        }
        return nums[start] + "->" + nums[end];
    }

Log in to reply
 

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