Java Solution - 1 while loop does it all


  • 0
    public class Solution {
        public List<String> summaryRanges(int[] nums) {
            List<String> res = new ArrayList<>(); 
            int n = nums.length; 
            if (n == 0) return res; 
            
            int i = 0, start = -1; 
            while (i < n) {
                if (start == -1) // in the beginning or previous range just closed, open a new range
                    start = i; 
                if ((i < n - 1 && (long)nums[i + 1] - nums[i] > 1) || i == n - 1) {
                    // 2 options: merge with the previous range or build a new range by itself. 
                    if (start == i) res.add("" + nums[i]);   // a new range by itself
                    else res.add(nums[start] + "->" + nums[i]);  // merge with the previous range. 
                    start = -1;  // after the range closed, need to reset start as -1. 
                } 
                i++;
            }
            return res; 
        }
    }

Log in to reply
 

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