力扣228 题目
题目链接
题目描述
基本思路
使用HashMap进行键的比较,值的赋值,键用来记录区间的开始位置,值用来记录区间长度,然后将结果加入ArrayList。
代码
class Solution {
public List<String> summaryRanges(int[] nums) {
Map<Integer, Integer> map = new HashMap<>();
List<String> s = new ArrayList<>();
int j = 1;//用来记录和起始位置的距离方便下一个连续元素进行判断
int w = 0;//用来在判断条件不成立时将上一个元素加入List
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(nums[i] - j)) {
map.put(nums[i] - j, map.get(nums[i] - j) + 1);
j++;
} else {
if (map.get(w) != null) {
if (map.get(w) == 0) {
int t = w;
s.add("" + t);
} else {
int q = w;
int t = map.get(w) + w;
s.add(q + "->" + t);
}
}
map.put(nums[i], 0);
w = nums[i];//记录下一个加入List的元素
j = 1;
}
}
if (map.get(w) != null) {//判断map中的最后一个元素
if (map.get(w) == 0) {
int t = w;
s.add("" + t);
} else {
int q = w;
int t = map.get(w) + w;
s.add(q + "->" + t);
}
}
return s;
}
}