并查集总结

leetcode中有关并查集的题目不多,这里现列举一道简单的题目,理解并查集的思想。

[b]Longest Consecutive Sequence[/b]
给定一个未排序的整型数组,找出最长的连续子序列。要求时间复杂度为O(n)。
例如:给定nums[] = {100, 4, 200, 1, 3, 2}
输出:4 最长连续子序列为(1,2,3,4)

我们用哈希处理元素是否被访问过,然后从第一个元素开始,分别检查它两边的元素,也就是对它进行加1和减1的操作,检查哈希表中是否存在,记录最大的个数。这就好像以节点构造了几棵树,只要找到最大的那棵树就是结果了。代码如下:

public class Solution {
public int longestConsecutive(int[] nums) {

HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
int max = 1;
if(nums == null || nums.length == 0) return 0;
for(int i : nums) hm.put(i, 0);

for(int i = 0; i < nums.length; i++) {
int count = 1;
int left = -1;
int right = 1;
if(hm.get(nums[i]) == 1) {
continue;
}
hm.put(nums[i], 1);
while(hm.containsKey(nums[i] + left)) {
hm.put(nums[i] + left, 1);
count ++;
left --;
}
while(hm.containsKey(nums[i] + right)) {
hm.put(nums[i] + right, 1);
count ++;
right ++;
}
max = Math.max(count, max);
}
return max;

}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值