【发布时间】:2022-01-30 13:02:21
【问题描述】:
public int longestConsecutive(int[] nums) {
Map<Integer, Boolean> numMap = new ConcurrentHashMap<>();
Map<Integer, Integer> maxMap = new ConcurrentHashMap<>();
for (int i : nums) {
numMap.put(i, false);
}
int max = 0;
for (int n : numMap.keySet()) {
numMap.remove(n);
if (maxMap.containsKey(n - 1)) {
maxMap.put(n, maxMap.get(n - 1) + 1);
max = Math.max(maxMap.get(n), max);
continue;
}
int lessThan = 0;
while (numMap.containsKey(n - lessThan - 1)) {
numMap.remove(n - 1);
lessThan++;
}
maxMap.put(n, lessThan + 1);
if (lessThan + 1 > max) {
max = lessThan + 1;
}
}
return max;
}
这是我对Longest Consecutive Sequence 问题的解决方案,它适用于所有 70 个案例中的 1 个。第 70 个案例数组的长度为 100,000。我检查了我的解决方案以了解数组的这个长度和其他长度,我观察到对于大小大于 65537 的数组,返回的最大值始终为 65537。我似乎无法弄清楚为什么会这样。 我想知道它是否与使用 ConcurrentHashmap 有关。
这是我的测试:
@Test
public void test() {
for (int i = 0; i < 100000; i++) {
int n = i;
int[] arr = new int[n];
for (int j = 0; j < n; j++) {
arr[j] = j;
}
assertEquals(n, longestConsecutive(arr));
}
}
测试在 65538 处失败,返回 65537。我还检查了一些大于该值的随机值,但同样的值对它们也失败了。
【问题讨论】:
-
您为什么要为
numMap使用地图?你并没有真正使用价值,是吗?为什么不改用 BitSet? -
@RealSkeptic 我不能使用集合,因为 ConcurrentModificationException
-
我说
BitSet。请查收。 -
@RealSkeptic 但我还需要 O(1) 次摊销访问。
-
@GoldCredential 不要在循环时修改它们。您可以简单地为此使用 HashSet,因为我们不关心元素的频率。
标签: java algorithm array-algorithms