[LeetCode] 228. Summary Ranges

Given a sorted integer array without duplicates, return the summary of its ranges.
Example 1:
Input: [0,1,2,4,5,7]
Output: ["0->2","4->5","7"]
Example 2:
Input: [0,2,3,4,6,8,9]
Output: ["0","2->4","6","8->9"]

Thought process:
This is similar to 56. Merge Intervals.

Solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
    public List<String> summaryRanges(int[] nums) {
        List<String> ranges = new ArrayList<>();
        if (nums.length == 0) {
            return ranges;
        }
        
        int start = nums[0];
        int end = nums[0];
        
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] == nums[i - 1] || nums[i] == nums[i - 1] + 1) {
                end = nums[i];
            } else {
                ranges.add(getRange(start, end));
                start = nums[i];
                end = nums[i];
            }
        }
        ranges.add(getRange(start, end));
        
        return ranges;
    }
    
    private String getRange(int start, int end) {
        if (start == end) {
            return "" + start;
        }
        return start + "->" + end;
    }
}

Time complexity: O(n).

Comments

Popular posts from this blog

[LeetCode] 714. Best Time to Buy and Sell Stock with Transaction Fee

[LeetCode] 269. Alien Dictionary

[LeetCode] 631. Design Excel Sum Formula