看到这道题 想到思路为 将数组排序后 在遍历中使用hashMap来存储
存储前先判断比当前数值小1的value值是否存在 存在即往map中添加当前数值 value为比当前数值小1的value来加1 若不存在则往map中添加当前数值 value为1
然后还要判断当前数值是否是重复数值 若重复则不进行判断 代码如下
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
class Solution {
public int longestConsecutive(int[] nums) {
HashMap<Integer,Integer> map = new HashMap<>();
Arrays.sort(nums);
for (Integer i : nums) {
if (map.get(i) != null){continue;}
else if (map.get(i - 1) != null){
map.put(i,map.get(i - 1) + 1);
map.remove(i - 1);
}else {
map.put(i,1);
}
}
Collection<Integer> values = map.values();
int max = 0;
for (Integer i : values) {
if (i > max){
max = i;
}
}
return max;
}
}
最终答案正确 但花费时长较长 思考如何优化
看了题解发现基本都是用set 来存储数组 因为set不可重复 会自动过滤掉重复的选项 减少了遍历耗费的时间 最快的解决方法是排序 也是没有想到 应该是map和set的底层操作会耗费较多时间 单纯使用循环遍历会比较快