【问题标题】:Best way to find elements in array X and also in array Y [duplicate]在数组 X 和数组 Y 中查找元素的最佳方法 [重复]
【发布时间】:2020-05-13 07:09:52
【问题描述】:

2 个有序数组中找到所有相等元素的最佳方法是什么?

我怎样才能让它通过 O(n) 完成?

【问题讨论】:

标签: algorithm time-complexity


【解决方案1】:

由于它们都已排序,因此您可以沿着它们两个方向走,直到到达任一端。假设整数看起来像这样(Java 示例)。您并没有真正定义如何处理重复项,所以我假设如果它们都是数组多次,您会希望看到它们。

public class TwoArraysWalkIntoABar {
    public static void main(String[] args) {
        int[] a = { 1, 2, 2, 2, 2, 3, 4, 4, 4, 4, 5, 6, 7, 8, 9 };
        int[] b = { 2, 4, 4, 4, 6, 8, 10, 12, 14, 16, 18, 20 };
        int ax = 0, bx = 0;

        while (true) {
            if (ax >= a.length || bx >= b.length) {
                break;
            } else if (a[ax] == b[bx]) {
                System.out.println("Match: " + a[ax]);
                ax++;
                bx++;
            } else if (a[ax] < b[bx]) {
                ax++;
            } else if (a[ax] > b[bx]) {
                bx++;
            }
        }
    }
}

结果:

Match: 2
Match: 4
Match: 4
Match: 4
Match: 6
Match: 8

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-19
    • 2018-04-14
    • 1970-01-01
    • 2022-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-14
    相关资源
    最近更新 更多