Java solution O(n)


  • 0
    A
    public class Solution {
        public List<String> summaryRanges(int[] nums) {
            List<String> res = new ArrayList<>();
            if (nums.length  > 0) {
                int start = 0;
                int prev = 0;
                for (int i = 1 ; i < nums.length; i++) {
                    if (!(nums[i] == nums[prev] + 1)) {
                        addInterval(start, prev, nums, res);
                        start = i;
                        prev = i;
                    }
                    else {
                        prev = i;
                    }
                }
                addInterval(start, nums.length -1, nums, res);
            }
            return res;
        }
        
        private void addInterval(int start, int end, int[] nums, List<String> result) {
            if (end - start > 0) {
                String s = nums[start] + "->" + nums[end];
                result.add(s);
            }
            else {
                result.add(String.valueOf(nums[start]));
            }
        }
    }

Log in to reply
 

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