根据岛屿问题二的问题进行扩展。
如果给定的m * n太大了而positions[][]中的元素个数很少怎么办 ? 比如说mn是100W * 100W的大小,那是不是每次初始化时,给定的数组空间太大了。这种时候改怎么进行优化?
可以尝试并查集介绍及原理中介绍的Map结构。
将postion中的 i 和 j ,拼接成Map中的Key,而后看parentMap中是否存在该Key,来确定是否要进行union操作。
代码
public static List<Integer> numIslands22(int m, int n, int[][] positions) {
List<Integer> ans = new ArrayList<>();
List<String> keys = new ArrayList<>();
//key : r_c拼接
for (int[] position : positions) {
keys.add(position[0] + "_" + position[1]);
}
UnionFind2 uf2 = new UnionFind2(keys);
for (int[] position : positions) {
ans.add(uf2.connect(position[0], position[1]));
}
return ans;
}
public static class UnionFind2 {
HashMap<String, String> parent;
HashMap<String, Integer> sizeMap;
int sets;
public UnionFind2(List<String> keys) {
parent = new HashMap<>();
sizeMap = new HashMap<>();
sets = 0;
for (String key : keys) {
parent.put(key, key);
sizeMap.put(key, 1);
}
}
public int connect(int m, int n) {
String key = String.valueOf(m) + "_" + String.valueOf(n);
if (!parent.containsKey(key)) {
parent.put(key, key);
sizeMap.put(key, 1);
sets++;
String keyUp = String.valueOf(m - 1) + "_" + String.valueOf(n);
String keyDown = String.valueOf(m + 1) + "_" + String.valueOf(n);
String keyLeft = String.valueOf(m) + "_" + String.valueOf(n - 1);
String keyRight = String.valueOf(m) + "_" + String.valueOf(n + 1);
union(key, keyUp);
union(key, keyDown);
union(key, keyLeft);
union(key, keyRight);
}
return sets;
}
public String findParent(String key) {
Stack<String> stack = new Stack<>();
while (key != parent.get(key)) {
stack.push(key);
key = parent.get(key);
}
while (!stack.isEmpty()) {
parent.put(stack.pop(), key);
}
return key;
}
public void union(String currentKey, String aroundKey) {
if (!parent.containsKey(currentKey) || !parent.containsKey(aroundKey)) {
return;
}
String key1 = findParent(currentKey);
String key2 = findParent(aroundKey);
if (key1 != key2) {
Integer size1 = sizeMap.get(key1);
Integer size2 = sizeMap.get(key2);
if (size1 >= size2) {
parent.put(key2, key1);
sizeMap.put(key1, size1 + size2);
} else {
parent.put(key1, key2);
sizeMap.put(key2, size1 + size2);
}
sets--;
}
}
}