LeetCode之Median of Two Sorted Arrays

桃扇骨 2022-08-05 12:16 291阅读 0赞

题目:There are two sorted arrays A and B of size m and n respectively.

Find the median of the two sorted arrays.

The overall run time complexity should be O(log(m + n)).

分析:这题很难,要求时间复杂度为log(m+n)。给出两个已经排好序的数组,要求找出两个数组中的中点元素。想了很久也没有想出怎么做,下面给出了三中解法,第一种是我自己写的,后面两种是我在网上看了,觉得比较好的解法。

代码:

  1. #include "stdafx.h"
  2. #include <iostream>
  3. #include <vector>
  4. #include <cstring>
  5. #include <algorithm>
  6. using namespace std;
  7. //寻找两个已排好序的数组的中点
  8. class Solution{
  9. public:
  10. int findMedianSortedArrays(int A[], int m, int B[], int n){
  11. int total = m + n;
  12. int am = 0;
  13. int bn = 0;
  14. vector<int> arr;
  15. for (int i = 0;i<total;i++){
  16. if (bn < n && am < m){
  17. if (A[am] > B[bn]){
  18. arr.push_back(B[bn++]);
  19. }else{
  20. arr.push_back(A[am++]);
  21. }
  22. }else if(bn >= n){
  23. arr.push_back(A[am++]);
  24. }else{
  25. arr.push_back(B[bn++]);
  26. }
  27. }
  28. return arr[total/2];
  29. }
  30. int findMedianSortedArrays2(int A[], int m, int B[], int n){
  31. int total = m + n;
  32. //判断奇偶,0x1十六进制1
  33. if (total & 0x1){ //奇
  34. return find_kth(A, m, B, n, total / 2 + 1);
  35. }
  36. else{ //偶
  37. return (find_kth(A, m, B, n, total / 2) + find_kth(A, m, B, n, total / 2 + 1)) / 2.0;
  38. }
  39. }
  40. int findMedianSortedArrays3(int A[], int m, int B[], int n){
  41. int total = m + n;
  42. int* a = new int[total];
  43. memcpy(a,A,sizeof(int)*m);
  44. memcpy(a+m,B,sizeof(int)*n);
  45. //sort(a,a + total, less<int>());
  46. sort(a,a + total);
  47. int rtn = a[total>>1]; //除以2,则右移一位
  48. delete a;
  49. return rtn;
  50. }
  51. private:
  52. //递归,求两个数组的中点
  53. int find_kth(int A[], int m, int B[], int n, int k) {
  54. if (m > n) return find_kth(B, n, A, m, k); //始终认为m<=n(前面数组比后面数组短),这样便于处理
  55. //递归终止条件
  56. if (m == 0) return B[k - 1];
  57. if (k == 1) return min(A[0], B[0]);
  58. //将k划分为两部分
  59. int ia = min(k / 2, m);
  60. int ib = k - ia;
  61. if (A[ia - 1] < B[ib - 1])
  62. return find_kth(A + ia, m - ia, B, n, k - ia);
  63. else if (A[ia - 1] > B[ib - 1])
  64. return find_kth(A, m, B + ib, n - ib, k - ib);
  65. else
  66. return A[ia - 1];
  67. }
  68. };

都认为第三种解法最好,的确,时间复杂度符合要求。可以说是要背下来的解法,这种解法可以解决求两个已排序数组中第k大的元素。

发表评论

表情:
评论列表 (有 0 条评论,291人围观)

还没有评论,来说两句吧...

相关阅读

    相关 LeetCodeMedian of Two Sorted Arrays

    第四题是找两个已经排序的数组的中位数,其实就是寻找两个排序数组的第k个数。寻找第k个数就需要把k均分到两个数组,可以用到结论如果a\[k/2-1\]小雨b\[k/2-1\],那