问题:
难度:easy
说明:
是在有序 int 数组内找到一段区间,区间内元素都是等差为 1 的。
问题链接:https://leetcode.com/problems/summary-ranges/
输入案例:
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"
我的代码:
好简单的题,感觉leetcode 每日一题有点够水的了,而且刚忙完项目,dp 忘了不少
class Solution {
private final static String line = "->";
private final static StringBuilder builder = new StringBuilder();
public List<String> summaryRanges(int[] nums) {
List<String> res = new ArrayList<String>();
int len = nums.length, begin = 0, end = 0;
for(int i = 0;i < len;i ++) {
if(nums[i] <= nums[end] + 1) {
end = i;
} else {
if(begin == end) res.add(String.valueOf(nums[end]));
else{
res.add(builder.append(nums[begin]).append(line).append(nums[end]).toString());
builder.setLength(0);
}
end = begin = i;
}
}
if(nums.length != 0) {
if(begin == end) res.add(String.valueOf(nums[end]));
else {
res.add(builder.append(nums[begin]).append(line).append(nums[end]).toString());
builder.setLength(0);
}
}
return res;
}
}