Code25 寻找两个正序数组的中位数

题目
代码
  • C
  • 思路
    • 有 int target = (nums1Size + nums2Size) / 2 + 1;
      • 若总数为奇数,则中位数为第 target 个 数,例如:共 3 个数,则 第 2 个 是中位数;
      • 若总数为偶数,则中位数为 (第 target - 1 个 数 + 第 target 个 数)/ 2,例如:共 4 个数,则 中位数为 第 2 个 + 第 3 个 数的和 / 2;
    • 也就是我们只需要总排序的第 target 个数,总数为偶数的话还需要第 target - 1 个数。
  • 代码
// 20ms 6.2MB
double findMedianSortedArrays(int* nums1,
                              int nums1Size,
                              int* nums2,
                              int nums2Size) {
  int target = (nums1Size + nums2Size) / 2 + 1;
  bool need_another = (nums1Size + nums2Size) % 2 == 0;
  int i = 0;
  int j = 0;

  int pre_min = 0;
  while (i < nums1Size || j < nums2Size){
    int min = 0;

    if (i < nums1Size && j < nums2Size){
      if (nums1[i] < nums2[j]) {
        min = nums1[i];
        ++i;
      }else{
        min = nums2[j];
        ++j;
      }
    } else if (i < nums1Size){
      min = nums1[i];
      ++i;
    }else {
      min = nums2[j];
      ++j;
    }

    if (i + j == target){
      if (need_another) {
        return (double)(pre_min + min) / 2;
      } else {
        return min;
      }
    }

    pre_min = min;
  }

  return 0;
}
  • C++
  • 思路
    • 全部排序到一个新的vector,然后计算中位数。
  • 代码
// 60ms 88.1MB 效率低很多
#include <algorithm>
#include <vector>
using namespace std;
class Solution {
 public:
  double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
    std::vector<int> vc;
    std::merge(nums1.begin(), nums1.end(), nums2.begin(), nums2.end(),
               std::back_inserter(vc));
    if (vc.size() % 2) {
      return vc[vc.size() / 2];
    } else {
      return (double)(vc[vc.size() / 2] + vc[(vc.size() - 1) / 2]) / 2;
    }
  }
};
测试
#include <iostream>

int main() {
  {
    int nums1[] = {1, 3};
    int nums1Size = sizeof(nums1) / sizeof(nums1[0]);
    int nums2[] = {2};
    int nums2Size = sizeof(nums2) / sizeof(nums2[0]);
    cout << findMedianSortedArrays(nums1, nums1Size, nums2, nums2Size) << endl;
  }
  {
    vector<int> nums1{1, 2};
    vector<int> nums2{3, 4};
    Solution s;
    cout << s.findMedianSortedArrays(nums1, nums2) << endl;
  }
  cin.get();
  return 0;
}
  • 结果
2
2.5
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值