https://leetcode.com/problems/longest-consecutive-sequence/
找到乱序数组之中的连续子数组长度。
解法一:并查集,保存两个数组id、size和一个map,并且记录当前最大连续子数组长度count。map的key为数组index,值为nums[index]。用该map为后续union做准备
public class Solution {
public int longestConsecutive(int[] nums) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
Union u = new Union(nums.length);
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(nums[i])) {
continue;
}
map.put(nums[i], i);
if (map.containsKey(nums[i] - 1)) {
u.union(i, map.get(nums[i] - 1));
}
if (map.containsKey(nums[i] + 1)) {
u.union(i, map.get(nums[i] + 1));
}
}
return u.count;
}
}
class Union {
int count;
int[] id;
int[] size;
public Union(int n) {
id = new int[n];
size = new int[n];
count = 1;
for (int i = 0; i < n; i++) { // 不要忘了并查集的初始化
id[i] = i;
size[i] = 1;
}
}
public int find(int i) {
if (id[i] == i) {
return i;
} else {
return find(id[i]);
}
}
public void union(int id1, int id2) {
int i = find(id1);
int j = find(id2);
// 重要,否则会重复加size
if (i == j) {
return;
}
if (size[i] > size[j]) {
id[j] = i;
size[i] += size[j];
} else {
id[i] = j;
size[j] += size[i];
}
count = Math.max(Math.max(size[i], size[j]), count);
}
}
public class Solution {
public int longestConsecutive(int[] nums) {
HashMap<Integer, Integer> map = new HashMap<>();
int res = 0;
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(nums[i])) {
continue;
}
int left = map.containsKey(nums[i] - 1) ? map.get(nums[i] - 1) : 0;
int right = map.containsKey(nums[i] + 1) ? map.get(nums[i] + 1) : 0;
int sum = left + right + 1;
res = Math.max(sum, res);
map.put(nums[i], sum);
map.put(nums[i] - left, sum);
map.put(nums[i] + right, sum);
}
return res;
}
}