【问题标题】:Why does the method not compute maximum greater than 65537?为什么该方法不计算大于 65537 的最大值?
【发布时间】: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


【解决方案1】:

ConcurrentModificationException 表示您的逻辑错误 - 您正在同时编辑和迭代地图。

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-10
    • 2012-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-07
    • 1970-01-01
    • 2013-05-13
    相关资源
    最近更新 更多