题目
题目链接:
https://www.nowcoder.com/practice/eac1c953170243338f941959146ac4bf
思路
核心:并查集
参考答案Java
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* max increasing subsequence
* @param arr int整型一维数组 the array
* @return int整型
*/
public int MLS (int[] arr) {
//并查集
// write code here
UF uf = new UF();
Set<Integer> set = new HashSet<>();
for (int i : arr) {
set.add(i);
}
for (int i : arr) {
uf.find(i);
if (set.contains(i - 1)) {
uf.union(i, i - 1);
}
if (set.contains(i + 1)) {
uf.union(i, i + 1);
}
}
int max = 0;
for (Integer integer : uf.parents.keySet()) {
max = Math.max(max, uf.size.get(integer));
//System.out.println(integer+" "+ uf.size.get(integer));
}
return max;
}
static class UF {
Map<Integer, Integer> parents = new HashMap<>();
Map<Integer, Integer> size = new HashMap<>();
Map<Integer, Integer> help = new HashMap<>();
int sets = 0;
public int find(int x) {
if (!parents.containsKey(x)) {
parents.put(x, x);
size.put(x, 1);
sets++;
}
int hi = 0;
while (x != parents.get(x)) {
help.put(hi++, x);
x = parents.get(x);
}
for (hi--; hi >= 0; hi--) {
parents.put(help.get(hi), x);
}
return x;
}
public void union(int a, int b) {
int f1 = find(a);
int f2 = find(b);
if (f1 != f2) {
int s1 = size.get(f1);
int s2 = size.get(f2);
if (s1 >= s2) {
size.put(f1, s1 + s2);
parents.put(f2, f1);
} else {
size.put(f2, s1 + s2);
parents.put(f1, f2);
}
sets--;
}
}
}
}
参考答案Go
package main
// import "fmt"
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* max increasing subsequence
* @param arr int整型一维数组 the array
* @return int整型
*/
func MLS(arr []int) int {
uf := UF{Parents: make(map[int]int), Size: make(map[int]int), Help: make(map[int]int), Sets: 0}
cache := map[int]int{}
for _, v := range arr {
cache[v] = v
}
for _, v := range arr {
uf.Find(v)
_, add := cache[v+1]
_, dec := cache[v-1]
if add {
uf.Union(v, v+1)
}
if dec {
uf.Union(v, v-1)
}
}
ans := 0
for _, v := range uf.Size {
if v > ans {
ans = v
}
}
return ans
}
type UF struct {
Parents map[int]int
Size map[int]int
Help map[int]int
Sets int
}
func (uf *UF) Find(x int) int {
_, ok := uf.Parents[x]
if !ok {
uf.Parents[x] = x
uf.Size[x] = 1
uf.Sets++
}
hi := 0
for x != uf.Parents[x] {
uf.Help[hi] = x
x = uf.Parents[x]
hi++
}
for hi--; hi >= 0; hi-- {
uf.Parents[uf.Help[hi]] = x
}
return x
}
func (uf *UF) Union(a, b int) {
f1 := uf.Find(a)
f2 := uf.Find(b)
if f1 != f2 {
s1 := uf.Size[f1]
s2 := uf.Size[f2]
if s1 >= s2 {
uf.Size[f1] = s1 + s2
uf.Parents[f2] = f1
} else {
uf.Size[f2] = s1 + s2
uf.Parents[f1] = f2
}
uf.Sets--
}
}