Java concise solution and easy understand


  • 0
    D

    My concise solution with O(n) :

    public List<String> summaryRanges(int[] nums) {
        List<String> res = new ArrayList<>();
        Integer start = null;
        int len = nums.length;
        for (int i = 0 ; i < len ; i++) {
            if (start == null) start = nums[i];
            if (i == len - 1 || (i < len - 1 && nums[i + 1] != nums[i] + 1)) {
                res.add(getString(start, nums[i]));
                start = null;
            }
        }
        return res;
    }
    
    String getString(int s, int e) {
        if (s != e) {
            return new StringBuilder().append(s).append("->").append(e).toString();
        } else {
            return String.valueOf(s);
        }
    }

Log in to reply
 

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