简体   繁体   English

我在哪里 go 错误地合并两个排序的 arrays。 它们需要在 O(1) 空间复杂度中合并

[英]Where did I go wrong to merge two sorted arrays. They need to be merged in O(1) space complexities

I am sorry.对不起。 I am new to this forum and also to programming.我是这个论坛的新手,也是编程的新手。 I have seen a question Merge without extra space and I tried solving it.我看到了一个没有额外空间的合并问题,我尝试解决它。 I haven't seen the editorial.我没看过社论。 I have tried writing the solution for the code, but it didn't seem to work online.我已经尝试为代码编写解决方案,但它似乎无法在线工作。 Although I tried a few test cases of my own which seem to work on my native ide.虽然我尝试了一些我自己的测试用例,它们似乎适用于我的原生 ide。 I want to know if my code is even right and I want to know how can I make it right.我想知道我的代码是否正确,我想知道如何使它正确。

Here's my code:这是我的代码:

void merge(int arr1[], int arr2[], int n, int m) {  // n is the size of arr1, m is size of arr2
    int i=0;
    while(i<n){
        if (arr1[i]>arr2[0])
        {
            swap(arr1[i], arr2[0]);
        }
        for (int j=1; j<m; j++){
            if (arr2[j-1]>arr2[j]){
                swap(arr2[j-1], arr2[j]);
            }
        }
        i++;
    }
}

I want the space complexity to be O(1) and the expected time complexity to be O((n+m) log(n+m)).我希望空间复杂度为 O(1),预期时间复杂度为 O((n+m) log(n+m))。

With that time complexity of O((n+m) log(n+m) you might do regular sort.使用O((n+m) log(n+m)的时间复杂度,您可以进行常规排序。

Creating correct iterator can be done but not trivial.可以创建正确的迭代器,但并非易事。

Other solution is to first partition elements to put the n lowest elements in arr1 , then sort each part:其他解决方案是首先对元素进行分区以将n最低元素放入arr1 ,然后对每个部分进行sort

void merge(int arr1[], int arr2[], int n, int m) {
    int i1 = 0;
    int i2 = 0;

    for (int i = 0; i != n; ++i) { // O(n)
        if (arr[i1] < arr2[i2]) { ++i1; }
        else { ++i2; }
    }
    // i1 + i2 == n
    for (int i = 0; i != i2; ++i) { // O(n)
        std::swap(arr2[i], arr1[i1 + i]);
    }

    std::sort(arr1, arr1 + n); // O(n log(n))
    std::sort(arr2, arr2 + m); // O(m log(m))
}

Demo .演示

  • O(n log(n)) < O(n log(n + m))
  • O(m log(m)) < O(m log(n + m))
  • O(n log(n)) + O(m log(m)) < O((n + m) log(n + m))

Note: I am even confident there exists a solution in O(n+m) without extra place.注意:我什至相信在O(n+m)中存在一个没有额外位置的解决方案。

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

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