Clean Java solution with a start pointer


  • 0
    Y

    The idea is: a start pointer is used to record the start position of connected range. it is initialized as -1, if there is connected range, which is the first if branch, we record that position as the start. If the pattern stops, we save the range if final result, which is the else if. Finally if the start == -1, which means this is a single number, just save it in the result.

    public class Solution {
        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.