Clean Java solution using two pointers


  • -1
    Y

    I used a start pointer, if the number is following a increasing order, we just set the start pointer as the begin of sequence. Once the pattern stops, if start has been set, meaning that we have more than 1 number in the sequence, we need to add the "->" in between. Otherwise, just add a single number.

       public List<String> summaryRanges(int[] nums) {
            List<String> res = new ArrayList<>();
            int start = -1, i = 0;
            while(i < nums.length) {
                if(i < nums.length-1 && nums[i] == nums[i+1]-1) {
                    if(start == -1) {
                        start = i;
                    }
                } else if(start != -1) {
                    res.add(nums[start] + "->" + nums[i]);
                    start = -1;
                } else {
                    res.add(nums[i]+"");
                }
                i++;
            }
            return res;
        }

Log in to reply
 

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