为什么该方法不计算大于65537的最大值


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;
}

这是我对最长连续序列问题的解决方案,它适用于70种情况中的所有情况,只有1种除外。第70个案例阵列的长度为100000。我检查了我的解决方案中的这个和其他长度的数组,发现对于大小大于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。我还检查了一些大于这个值的随机值,但在相同的值下也失败了。

ConcurrentModificationException表示您的逻辑错误——您正在同时编辑和迭代映射。

迭代numMap.keySet()nums的值-您应该可以将外循环更改为:

for (int n : nums) {
...
}

这避免了在执行编辑时迭代器上的ConcurrentModificationException。您不需要使用ConcurrentHashMap而不是HashMap——在这种情况下,两者都应该可以正常工作,并且测试可以通过100000。

最新更新