[LeetCode]128. 最长连续序列(java实现)
1. 题目
2. 读题(需要重点注意的东西)
解法1:首先能想到一个解法是暴力法,即用暴力循环;时间复杂度为O(n2),题目要求用O(n)的时间复杂度。
解法2:使用哈希表。主要思路是用哈希集合存储数组的值(哈希表有去重的功能),完成去重,再遍历查找哈希集合中的最长子序列。 整个算法最妙的地方在于判断了是否存在前置元素,因此时间复杂度大大缩小了,可以视为O(n)。
3. 解法
解法2:
class Solution {
// 查找问题,即查找数组中当前值的下一个值是否存在,存在则加1
public int longestConsecutive(int[] nums) {
Set<Integer> hash = new HashSet<Integer>();
for(int x : nums) hash.add(x);
// for(int x : nums) 相当于for(int i = 0; i < nums.length ; i++) x = nums[i];
int res = 0;
for(int x : hash)
{
// 因为判断了是否存在前置元素,因此时间复杂度大大缩小了,可以视为O(n),这里是整个算法最妙的地方
if(!hash.contains(x-1))
{
int y = x;
while(hash.contains(y + 1)) y++;
res = Math.max(res, y - x + 1);
}
}
return res;
}
}
}
for(int x : nums) hash.add(x);
!hash.contains(x-1);
等代码可在Java数据结构—HashMap(哈希表及其基本操作)(含hashset)中得到介绍