[Java] Summary Ranges
Feel free to leave a comment or contact me if you spot any errors or have feedback. Iβm always open to learning!
[Java] Summary Ranges
LeetCode Problem #228 π LeetCode Link
Espeically, this problem is in the Must-do List for Interview Prep in Leetcode.
Description
You are given a sorted unique integer array nums.
A range [a,b] is the set of all integers from a to b (inclusive).
Return the smallest sorted list of ranges that cover all the numbers in the array exactly. That is, each element of nums is covered by exactly one of the ranges, and there is no integer x such that x is in one of the ranges but not in nums.
Each range [a,b] in the list should be output as:
- βa->bβ if a != b
 - βaβ if a == b
 
Example
Example 1
- Input: nums = [0,1,2,4,5,7]
 - Output: [β0->2β,β4->5β,β7β]
 - Explanation: The ranges are: [0,2] β> β0->2β [4,5] β> β4->5β [7,7] β> β7β
 
Example 2
- Input: nums = [0,2,3,4,6,8,9]
 - Output: [β0β,β2->4β,β6β,β8->9β]
 - Explanation: The ranges are: [0,0] β> β0β [2,4] β> β2->4β [6,6] β> β6β [8,9] β> β8->9β
 
Constraints
- 0 <= nums.length <= 20
 - -231 <= nums[i] <= 231 - 1
 - All the values of nums are unique.
 - nums is sorted in ascending order.
 
My Solution
My approach was using Hashmap as I wanted to store key and value, here frequency of letter. But after looking over othersβ solutions. It would be better to use int array because ransomNote and magazone consist of lowercase English letters only, which means I can use ASCII.
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
32
class Solution {
    public List<String> summaryRanges(int[] nums) {
        ArrayList<String> rangeList = new ArrayList<>();
        if (nums.length > 0) {
            int start = nums[0];
            int end = nums[0];
            for (int i = 1; i < nums.length; ++i) {
                if (nums[i] - nums[i-1] == 1) {
                    end = nums[i];
                } else {
                    if (start == end) {
                        rangeList.add(Integer.toString(start));
                    } else {
                        rangeList.add(Integer.toString(start) + "->" + Integer.toString(end));
                    }
                    start = nums[i];
                    end = nums[i];
                }
            }
            if (start == end) {
                rangeList.add(Integer.toString(start));
            } else {
                rangeList.add(Integer.toString(start) + "->" + Integer.toString(end));
            }
        }
        return rangeList;
    }
}