Summary interval
Title description: Given an ordered integer array nums with no repeated elements.
Returns a list of the smallest ordered range ranges that happen to cover all the numbers in the array. In other words, each element of nums is exactly covered by a certain range, and there is no number x that belongs to a certain range but does not belong to nums.
Each interval range [a,b] in the list should be output in the following format:
- "a->b" if a != b
- "a" if a == b
Please refer to LeetCode official website for example description.
Source: LeetCode
Link: https://leetcode-cn.com/problems/summary-ranges/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.
Solution 1: Traverse the array
First, initialize a result to store and return the result, and then the processing process is as follows:
- If nums is null or nums has no element, return result directly;
- If nums has only one element, add the unique element to result and return result;
Initialize start and end as the first element of the array, and then traverse the array from the first position:
- If the current element is greater than end by 1, it means it is continuous, and the current element is assigned to end;
- Otherwise, determine whether start is equal to end, that is, add the current interval to the result, and then assign the current element to start and end.
After the traversal is completed, the last interval is added to the result, and the result is returned.
import java.util.ArrayList;
import java.util.List;
public class LeetCode_228 {
public static List<String> summaryRanges(int[] nums) {
List<String> result = new ArrayList<>();
if (nums == null || nums.length == 0) {
return result;
}
if (nums.length == 1) {
result.add(String.valueOf(nums[0]));
return result;
}
int start = nums[0], end = nums[0];
for (int i = 1; i < nums.length; i++) {
if (nums[i] == end + 1) {
end = nums[i];
} else {
if (start == end) {
result.add("" + start);
} else {
result.add(start + "->" + end);
}
start = end = nums[i];
}
}
if (start == end) {
result.add("" + start);
} else {
result.add(start + "->" + end);
}
return result;
}
public static void main(String[] args) {
int[] nums = new int[]{0, 1, 2, 4, 5, 7};
for (String summaryRange : summaryRanges(nums)) {
System.out.println(summaryRange);
}
}
}
[Daily Message] You have to be a dark horse rushing out instead of falling stars.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。