Very easy Java 10-line solution


  • 1

    Handle the last batch in one loop to simplify. I think mine is much simpler than some high upvoted one. :)

        // j is start index, i is end.
        public List<String> summaryRanges(int[] nums) {
            List<String> ret = new ArrayList<>();
            int n = nums.length;
            for (int i = 1, j = 0; i <= n; i++) {
                if (i == n || nums[i - 1] != nums[i] - 1) {
                    ret.add(j == i - 1 ? nums[j] + "" : nums[j] + "->" + nums[i - 1]);
                    j = i;
                }
            }
            return ret;
        }
    

  • 1
    Z

    neat solution but hard to follow


Log in to reply
 

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