Difficulty : Easy
Related Topics : Array
You are given a sorted unique integer array
nums
.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 integerx
such thatx
is in one of the ranges but not innums
.Each range
[a,b]
in the list should be output as:
"a->b"
ifa != b
"a"
ifa == b
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"
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"
Input: nums = [] Output: []
Input: nums = [-1] Output: ["-1"]
Input: nums = [0] Output: ["0"]
0 <= nums.length <= 20
-2^31 <= nums[i] <= 2^31 - 1
- All the values of
nums
are unique.
- mine
- Java
Runtime: 5 ms, faster than 86.58%, Memory Usage: 37.7 MB, less than 8.82% of Java online submissions
public List<String> summaryRanges(int[] nums) { List<String> res = new ArrayList<>(); int n = nums.length; if(n == 0) return res; if(n == 1){ res.add(String.valueOf(nums[0])); return res; } int s = nums[0]; int t = s; for(int i = 1; i < n; i++){ if(i + 1 == n){ if(nums[i] == t + 1){ res.add(s + "->" + nums[i]); }else{ if(s == t){ res.add(String.valueOf(s)); }else{ res.add(s + "->" + t); } res.add(String.valueOf(nums[i])); } }else{ if(nums[i] == t + 1){ t++; }else{ if(s == t){ res.add(String.valueOf(s)); }else{ res.add(s + "->" + t); } s = nums[i]; t = s; } } } return res; }
- Java
- the most votes
Runtime: 0 ms, faster than 100.00%, Memory Usage: 37.2 MB, less than 8.82% of Java online submissions
public List<String> summaryRanges(int[] nums) { List<String> res = new ArrayList<>(); if (nums == null || nums.length == 0) { return res; } int anchor = 0; for (int i = 0; i < nums.length; i ++) { anchor = i; while(i + 1 < nums.length && nums[i + 1] - nums[i] == 1) { i ++; } res.add(getRange(nums[anchor], nums[i])); } return res; } private String getRange(int start, int end) { StringBuilder sb = new StringBuilder(); if (start == end) { sb.append(start); } else { sb.append(start).append("->").append(end); } return sb.toString(); }