【hashset】【hash查找元素O(1 )时间复杂度】Leetcode 128. 最长连续序列
- 解法1 hashmap
- 解法2 不满足题设 排序+遍历
---------------🎈🎈题目链接🎈🎈-------------------
解法1 hashmap
核心思想
利用了hashmap查找元素的时间复杂度为O(1)的特性
当前的数字nums-1在hashmap中存在的时候就跳过这个数字
时间复杂度O(N)
时间复杂度分析
1、构建 HashSet 并将 nums 中的元素放入 HashSet 中的时间复杂度为 O(N)。
2、然后,遍历 HashSet,对于每个元素,我们检查它的前一个元素是否在 HashSet 中,这一步遍历了 HashSet,因此时间复杂度为 O(N)。
3、在内部的 while循环中,我们可能会访问到连续的多个元素,但在整个过程中,每个元素最多被访问一次,因此内部的 while 循环总共最多执行 N 次。因此,内部while 循环的时间复杂度也是 O(N)。
> 综上所述,总的时间复杂度是 O(N) + O(N) + O(N) = O(N)。
空间复杂度O(N)
class Solution {
public int longestConsecutive(int[] nums) {
// 利用了hashmap查找元素的时间复杂度为O(1)的特性
// 当当前的数字nums-1在hashmap中存在的时候就跳过这个数字
HashSet<Integer> myhashset = new HashSet<>(); // 新建hashset把nums的元素塞进去 时间复杂度O(N)
for(int num:nums){
myhashset.add(num);
}
int result = 0;
// 遍历hashset 时间复杂度O(N)
for(int num:myhashset){
if(myhashset.contains(num-1)){// 当前的数字nums-1在hashmap中存在的时候就跳过这个数字
continue;
}
int cur = num ;
int count = 1;
// 接下来就是找当前num 后面+1 +2 +3的数
while(myhashset.contains(cur+1)){
count++;
cur = cur+1;
}
if(result<count) result=count;
}
return result;
}
}
解法2 不满足题设 排序+遍历
时间复杂度O(N)
时间复杂度分析:
1、首先,数组排序的时间复杂度为 O(n log n),其中 n 是数组 nums 的长度。
2、然后,通过一次遍历排序后的数组,计算最长连续序列的长度。在遍历过程中,对于每个元素,只需常数时间内的比较操作,因此遍历的时间复杂度为 O(n)。
综上所述,总的时间复杂度是排序的时间复杂度加上遍历的时间复杂度,即 O(n log n) + O(n) = O(n log n)。
空间复杂度O(1)
class Solution {
public int longestConsecutive(int[] nums) {
Arrays.sort(nums);
int result =0;
int finalresult =0;
for(int i =0; i < nums.length; i++){
if(i==0){
result=1;
}
if(i>0 && nums[i]-nums[i-1]==1){
result++;
}
if(i>0 && nums[i]-nums[i-1]>1){
if(result>finalresult){
finalresult = result;
}
result=1;
}
}
return Math.max(result,finalresult);
}
}