4.12 哈希表 乱序数组最长递增序列

哈希表大致有以下两类
1.hashmap(特点:可以存储key和value,keyset类似于hashset,不能重复,valueset则是keyset的一个映射)(在需要用到映射的时候考虑hashmap)
2.hashset(特点:查询的时间复杂度为O(1),里面存储的数据不能重复)

本题:
我的代码:
public int longestConsecutive(int[] nums) {
if (nums.length == 0) {return 0;}
ArrayList list = new ArrayList<>();
for (int num : nums) {
if(!list.contains(num))list.add(num);
}
list.sort(null);
int max = 0;
int count =1;
for (int i = 0; i < list.size() - 1; i++) {
if (list.get(i) + 1 == list.get(i + 1)) {
count++;
} else if (list.get(i) != list.get(i + 1)) {
max = Math.max(max, count);
count = 1;
}
}
return Math.max(max, count);

}

时间复杂度高

用哈希表的代码:
public int longestConsecutive(int[] nums) {
if (nums.length == 0) return 0;
HashSet set = new HashSet<>();
for (int num : nums) {
set.add(num);
}
int max = 0;
for (int num : nums) {
if (!set.contains(num - 1)) {
int currentNum = num;
int count = 1;
while (set.contains(currentNum + 1)) {
count++;
currentNum++;
}
max = Math.max(max, count);
}
}
return max;
}
利用哈希表查询快的特点,多次查询
并且运用数学思想(如果一个数前面的数字不存在在哈希表中,则最长递增子序列的开头一定是这个数字或者有类似特点的数字)

posted @ 2025-04-12 10:42  Toby0919  阅读(10)  评论(0)    收藏  举报