📌  相关文章
📜  使用堆在O(1)多余空间中合并两个排序的数组

📅  最后修改于: 2021-04-24 19:16:49             🧑  作者: Mango

给定两个排序数组arr []brr []的大小NM ,任务是合并两个给定数组,以使它们形成结合两个数组元素的整数排序序列。

例子:

天真的方法:有关合并两个给定数组的最简单方法,请参阅合并两个排序的数组。
时间复杂度: O(N * M)
辅助空间: O(1)

空间优化方法:请参阅合并两个排序的数组,并使用O(1)额外的空间来合并两个给定的数组,而不使用任何额外的内存。
时间复杂度: O(N * M)
辅助空间: O(1)

有效的空间优化方法:指的是有效地将两个排序的数组与O(1)的额外空间合并,以在不使用任何额外内存的情况下合并两个给定的数组。
时间复杂度: O((N + M)* log(N + M))
辅助空间: O(1)

基于的方法:可以使用堆解决问题。这个想法是遍历arr []数组,并将arr [i]的值与brr [0]进行比较,并检查arr [i]是否大于brr [0] 。如果发现为true,则交换(arr [i],brr [0)并在brr []上执行heapify操作。请按照以下步骤解决问题:

  • 遍历数组arr []并将arr [i]的值与brr [0]比较,并检查arr [i]是否大于brr [0] 。如果发现为true,则交换(arr [i],brr [0)并在brr []上执行heapify操作。
  • 最后,对数组brr []排序并打印两个数组。

下面是上述方法的实现:

C++
// C++ program to implement
// the above approach
 
#include 
using namespace std;
 
// Function to perform min heapify
// on array brr[]
void minHeapify(int brr[], int i, int M)
{
 
    // Stores index of left child
    // of i.
    int left = 2 * i + 1;
 
    // Stores index of right child
    // of i.
    int right = 2 * i + 2;
 
    // Stores index of the smallest element
    // in (arr[i], arr[left], arr[right])
    int smallest = i;
 
    // Check if arr[left] less than
    // arr[smallest]
    if (left < M && brr[left] < brr[smallest]) {
 
        // Update smallest
        smallest = left;
    }
 
    // Check if arr[right] less than
    // arr[smallest]
    if (right < M && brr[right] < brr[smallest]) {
 
        // Update smallest
        smallest = right;
    }
 
    // if i is not the index
    // of smallest element
    if (smallest != i) {
 
        // Swap arr[i] and arr[smallest]
        swap(brr[i], brr[smallest]);
 
        // Perform heapify on smallest
        minHeapify(brr, smallest, M);
    }
}
 
// Function to merge two sorted arrays
void merge(int arr[], int brr[],
           int N, int M)
{
 
    // Traverse the array arr[]
    for (int i = 0; i < N; ++i) {
 
        // Check if current element
        // is less than brr[0]
        if (arr[i] > brr[0]) {
 
            // Swap arr[i] and brr[0]
            swap(arr[i], brr[0]);
 
            // Perform heapify on brr[]
            minHeapify(brr, 0, M);
        }
    }
 
    // Sort array brr[]
    sort(brr, brr + M);
}
 
// Function to print array elements
void printArray(int arr[], int N)
{
 
    // Traverse array arr[]
    for (int i = 0; i < N; i++)
        cout << arr[i] << " ";
}
 
// Driver Code
int main()
{
    int arr[] = { 2, 23, 35, 235, 2335 };
    int brr[] = { 3, 5 };
    int N = sizeof(arr) / sizeof(arr[0]);
    int M = sizeof(brr) / sizeof(brr[0]);
 
    // Function call to merge
    // two array
    merge(arr, brr, N, M);
 
    // Print first array
    printArray(arr, N);
 
    // Print Second array.
    printArray(brr, M);
 
    return 0;
}


Java
// Java program to implement
// the above approach
import java.util.*;
class GFG{
 
// Function to perform
// min heapify on array
// brr[]
static void minHeapify(int brr[],
                       int i, int M)
{
  // Stores index of left
  // child of i.
  int left = 2 * i + 1;
 
  // Stores index of right
  // child of i.
  int right = 2 * i + 2;
 
  // Stores index of the smallest
  // element in (arr[i], arr[left],
  // arr[right])
  int smallest = i;
 
  // Check if arr[left] less than
  // arr[smallest]
  if (left < M && brr[left] <
      brr[smallest])
  {
    // Update smallest
    smallest = left;
  }
 
  // Check if arr[right] less
  // than arr[smallest]
  if (right < M && brr[right] <
      brr[smallest])
  {
    // Update smallest
    smallest = right;
  }
 
  // if i is not the index
  // of smallest element
  if (smallest != i)
  {
    // Swap arr[i] and
    // arr[smallest]
    int temp = brr[i];
    brr[i] =  brr[smallest];
    brr[smallest] = temp;
 
    // Perform heapify on smallest
    minHeapify(brr, smallest, M);
  }
}
 
// Function to merge two
// sorted arrays
static void merge(int arr[], int brr[],
                  int N, int M)
{
  // Traverse the array arr[]
  for (int i = 0; i < N; ++i)
  {
    // Check if current element
    // is less than brr[0]
    if (arr[i] > brr[0])
    {
      // Swap arr[i] and brr[0]
      int temp = arr[i];
      arr[i] = brr[0];
      brr[0] = temp;
 
      // Perform heapify on brr[]
      minHeapify(brr, 0, M);
    }
  }
 
  // Sort array brr[]
  Arrays.sort(brr);
}
 
// Function to print array
// elements
static void printArray(int arr[],
                       int N)
{
  // Traverse array arr[]
  for (int i = 0; i < N; i++)
    System.out.print(arr[i] + " ");
}
 
// Driver Code
public static void main(String[] args)
{
  int arr[] = {2, 23, 35, 235, 2335};
  int brr[] = {3, 5};
  int N = arr.length;
  int M = brr.length;
 
  // Function call to merge
  // two array
  merge(arr, brr, N, M);
 
  // Print first array
  printArray(arr, N);
 
  // Print Second array.
  printArray(brr, M);
}
}
 
// This code is contributed by Rajput-Ji


Python3
# Python3 program to implement
# the above appraoch
 
# Function to perform min heapify
# on array brr[]
def minHeapify(brr, i, M):
 
    # Stores index of left child
    # of i.
    left = 2 * i + 1
 
    # Stores index of right child
    # of i.
    right = 2 * i + 2
 
    # Stores index of the smallest element
    # in (arr[i], arr[left], arr[right])
    smallest = i
 
    # Check if arr[left] less than
    # arr[smallest]
    if (left < M and brr[left] < brr[smallest]):
 
        # Update smallest
        smallest = left
 
    # Check if arr[right] less than
    # arr[smallest]
    if (right < M and brr[right] < brr[smallest]):
 
        # Update smallest
        smallest = right
 
    # If i is not the index
    # of smallest element
    if (smallest != i):
 
        # Swap arr[i] and arr[smallest]
        brr[i], brr[smallest] = brr[smallest], brr[i]
 
        # Perform heapify on smallest
        minHeapify(brr, smallest, M)
 
# Function to merge two sorted arrays
def merge(arr, brr, N, M):
 
    # Traverse the array arr[]
    for i in range(N):
 
        # Check if current element
        # is less than brr[0]
        if (arr[i] > brr[0]):
 
            # Swap arr[i] and brr[0]
            arr[i], brr[0] = brr[0], arr[i]
 
            # Perform heapify on brr[]
            minHeapify(brr, 0, M)
 
    # Sort array brr[]
    brr.sort()
 
# Function to print array elements
def printArray(arr, N):
 
    # Traverse array arr[]
    for i in range(N):
        print(arr[i], end = " ")
 
# Driver code
if __name__ == '__main__':
 
    arr = [ 2, 23, 35, 235, 2335 ]
    brr = [3, 5]
    N = len(arr)
    M = len(brr)
 
    # Function call to merge
    # two array
    merge(arr, brr, N, M)
 
    # Print first array
    printArray(arr, N)
 
    # Print Second array.
    printArray(brr, M)
 
# This code is contributed by Shivam Singh


C#
// C# program to implement
// the above approach
using System;
 
class GFG{
 
// Function to perform
// min heapify on array
// brr[]
static void minHeapify(int []brr,
                       int i, int M)
{
   
  // Stores index of left
  // child of i.
  int left = 2 * i + 1;
 
  // Stores index of right
  // child of i.
  int right = 2 * i + 2;
 
  // Stores index of the smallest
  // element in (arr[i], arr[left],
  // arr[right])
  int smallest = i;
 
  // Check if arr[left] less than
  // arr[smallest]
  if (left < M && brr[left] <
      brr[smallest])
  {
     
    // Update smallest
    smallest = left;
  }
 
  // Check if arr[right] less
  // than arr[smallest]
  if (right < M && brr[right] <
      brr[smallest])
  {
     
    // Update smallest
    smallest = right;
  }
 
  // If i is not the index
  // of smallest element
  if (smallest != i)
  {
     
    // Swap arr[i] and
    // arr[smallest]
    int temp = brr[i];
    brr[i] =  brr[smallest];
    brr[smallest] = temp;
 
    // Perform heapify on smallest
    minHeapify(brr, smallest, M);
  }
}
 
// Function to merge two
// sorted arrays
static void merge(int []arr, int[]brr,
                  int N, int M)
{
   
  // Traverse the array []arr
  for(int i = 0; i < N; ++i)
  {
     
    // Check if current element
    // is less than brr[0]
    if (arr[i] > brr[0])
    {
       
      // Swap arr[i] and brr[0]
      int temp = arr[i];
      arr[i] = brr[0];
      brr[0] = temp;
 
      // Perform heapify on brr[]
      minHeapify(brr, 0, M);
    }
  }
 
  // Sort array brr[]
  Array.Sort(brr);
}
 
// Function to print array
// elements
static void printArray(int []arr,
                       int N)
{
   
  // Traverse array []arr
  for(int i = 0; i < N; i++)
    Console.Write(arr[i] + " ");
}
 
// Driver Code
public static void Main(String[] args)
{
  int []arr = { 2, 23, 35, 235, 2335 };
  int []brr = {3, 5};
  int N = arr.Length;
  int M = brr.Length;
 
  // Function call to merge
  // two array
  merge(arr, brr, N, M);
 
  // Print first array
  printArray(arr, N);
 
  // Print Second array.
  printArray(brr, M);
}
}
 
// This code is contributed by Amit Katiyar


输出:
2 3 5 23 35 235 2335












时间复杂度: O((N + M)* log(M))
辅助空间: O(1)

高效方法:指合并两个排序的数组以有效地合并两个给定的数组。
时间复杂度: O(N + M)
辅助空间: O(N + M)

想要从精选的最佳视频中学习并解决问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”