4. 寻找两个正序数组的中位数(LeetCode算法题)

方法一、暴力解法
即先将两个有序数组合并为一个有序数组,然后求得此有序数组的中位数。因此算法的核心是归并两个有序数组,可以借鉴归并排序里归并两个有序数组的方法。此法时间复杂度为O(m+n),因为需要遍历两个数组所有元素,空间复杂度为O(m+n),因为需要开辟新数组存储这两个数组的所有元素。

#include 
#include 

double findMedienSortedArr(int *arr1, int arr1Size, int *arr2, int arr2Size)
{

  //merge array
  int size = arr1Size + arr2Size;
  int *arr = (int *)malloc(size * sizeof(int));
  int arr1Index = 0;
  int arr2Index = 0;
  double medien;
  for (int index = 0; index < size; index++) {
    if (arr1Index < arr1Size && arr2Index < arr2Size)
    {
      if (arr1[arr1Index] <= arr2[arr2Index])
      {
        arr[index] = arr1[arr1Index];
        arr1Index++;
      }
      else
      {
        arr[index] = arr2[arr2Index];
        arr2Index++;
      }
    }
    else if (arr1Index < arr1Size && arr2Index >= arr2Size)
    {
      arr[index] = arr1[arr1Index];
      arr1Index++;
    }
    else if (arr1Index >= arr1Size && arr2Index < arr2Size)
    {
      arr[index] = arr2[arr2Index];
      arr2Index++;
    }
  }
  // 打印合并后的数组,测试的代码,可以注释掉
  //for (int j = 0; j < size; j++) {
  //  printf("%d ", arr[j]);
  //}
  
  if (size % 2 == 0)
  {
    medien = (double)(arr[size / 2 - 1] + arr[size / 2]) / 2;
  }
  else
  {
    medien = arr[size / 2];
  }
  return medien;
}
int main(void)
{
  int arr1[] = {2, 4, 5, 7, 9, 29, 67};
  int arr2[] = {3, 6, 8, 9, 10, 13, 18};
  int size1 = sizeof(arr1) / sizeof(*arr1);
  int size2 = sizeof(arr2) / sizeof(*arr2);
  printf("arr length: %d %d\n", size1, size2);
  double medien = findMedienSortedArr(arr1, size1, arr2, size2);
  printf("\n");
  for (int i = 0; i < size1; i++)
  {
    printf("%d ", arr1[i]);
  }
  printf("\n");
  for (int j = 0; j < size2; j++)
  {
    printf("%d ", arr2[j]);
  }
  printf("\n");
  printf("medien is %f", medien);
  printf("\n");
}

你可能感兴趣的:(算法)