Java Solution similar to Merge Intervals


  • 0
    E

    I found this question quite similar to merge intervals, so again I use start and end pointers to mark a range, in each iteration I either increase the end pointer(meaning that we are still at current range) or add range to result and start a new range, do remember to add the last range outside the loop as we did in merge intervals.

    public List<String> summaryRanges(int[] nums) {
            List<String> result = new ArrayList<>();
            if (nums == null || nums.length == 0) {
                return result;
            }
            int start = 0, end = 0;
            for (int i = 1; i < nums.length; i++) {
                if (nums[i] == nums[i - 1] + 1) {
                    end = i;
                } else {
                    StringBuilder sb = new StringBuilder();
                    if (start != end) {
                        sb.append(nums[start]);
                        sb.append("->");
                        sb.append(nums[end]);
                    } else {
                        sb.append(nums[start]);
                    }
                    result.add(sb.toString());
                    start = i;
                    end = i;
                }
            }
            if (start != end) {
                StringBuilder sb = new StringBuilder();
                sb.append(nums[start]);
                sb.append("->");
                sb.append(nums[end]);
                result.add(sb.toString());
            } else {
                StringBuilder sb = new StringBuilder();
                sb.append(nums[start]);
                result.add(sb.toString());
            }
            return result;
        }
    

Log in to reply
 

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