Simple Java solution, clean and straight forward


  • 2
    W
    public class Solution {
    public List<String> summaryRanges(int[] nums) {
        int i=0;
        List<String> result=new ArrayList<String>();
        while(i<nums.length){
            String s="";
            s+=nums[i];
            if(i<nums.length-1&&nums[i]+1==nums[i+1]){
                s+="->";
                while(i<nums.length-1&&nums[i]+1==nums[i+1]){
                    i++;
                }
                s+=nums[i];
            }
            result.add(s);
            s=new String();
            i++;
        }
        return result;
    }
    

    }


  • 0
    U

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

        int beginVal = nums[0];
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] + 0L - nums[i-1] > 1) {
                results.add(constructRange(beginVal, nums[i-1]));
                beginVal = nums[i];
            }
        }
        
        results.add(constructRange(beginVal, nums[nums.length-1]));
        return results;
    }
    
    private String constructRange(int beginVal, int endVal) {
        if (beginVal == endVal) {
            return beginVal + "";
        }
        return beginVal + "->" + endVal;
    }
    

    }


Log in to reply
 

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