Java Solution with clear logic


  • 0
    C
    public List<String> summaryRanges(int[] nums) {
            List<String> ans = new ArrayList<String>();
            //sanity check
            if (nums == null || nums.length == 0) return ans;
            int prev = nums[0], start = nums[0], end = nums[0];
            
            for (int i = 1; i < nums.length; i++){
                if (nums[i] != prev + 1){
                    if (start == end) ans.add(start + "");
                    else ans.add(start + "->" + end);
                    start = nums[i];
                }
                end = nums[i];
                prev = nums[i];
            }
            
            if (start == end) ans.add(start + "");
            else ans.add(start + "->" + end);
            
            return ans;
        }
    

Log in to reply
 

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