繁体   English   中英

查找数组中所有数字的O时间复杂度大

[英]Big O Time complexity for Find All Numbers Disappeared in an Array

在此期间,我正在解决此代码练习。 我不知道我当前的解决方案是否仍在O(n)运行时。

下面我介绍我的解决方案。

查找数组中消失的所有数字

给出一个整数数组,其中1 <= a [i] <= n(n =数组大小),一些元素出现两次,另一些元素出现一次。

查找[1,n]包含的所有未出现在此数组中的元素

您能在没有额外空间的情况下在O(n)运行时执行此操作吗?

例:

输入:[4、3、2、7、8、2、3、1]

输出:[5、6]

public static void main(String[] args) {
    findAllNumbersDisappeared(new int[] { 4,3,2,7,8,2,3,1});
}

/* the idea is that since we have a size _n_ array and it has numbers from 1 to n, 
 * given that are repeated numbers, we can iterate over the array and 
 * keep placing the elements in the position equal to their value 
 * (i.e. 1 is placed in the first position, 2 in the second, 3 in the third, and so on)
 * Once that is done by swapping the elements, we iterate over the array again and 
 * compare the position with the value at that position. 
 * 
 * For the positions where they don't match, 
 * it means that whereas it should ideally have had the same value at that position (if there were no repeats), 
 * that positional value represents the missing number.
 * */
public static void findAllNumbersDisappeared(int[] arr) {
    for (int i = 0; i < arr.length; i++) {
        while (arr[i] != (i+1) && arr[i] != arr[arr[i]-1]) {
            swap(arr, i, arr[i]-1);
        }
    }

    for (int i = 0; i < arr.length; i++) {
        if (arr[i] != (i+1)) {
            System.out.println(i+1);
        }
    }
}

private static void swap(int[] arr, int i, int j) {
    int t = arr[i];
    arr[i] = arr[j];
    arr[j] = t;
}

也许我对大O理论感到困惑。 第一个循环在N个项目上进行迭代(其中N是数组的长度,所以它是O(n)),内部while在整个程序流中执行的次数不超过N次。

我不认为这个程序是O(n ^ 2),我认为是在O(n)和O(n log n)之间。 您可以支持我确定该解决方案的正确时间复杂度吗?

您的解决方案是O(N),但我认为这是不正确的。 (测试!)

提示:有一种O(N)算法可以真正解决该问题。

(这些提示旨在使您朝正确的方向进行思考。我想您可能已经在大多数地方了,但是我希望您自己找到正确的解决方案。最大程度地学习/建立自信。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM