LeetCode--4

本文探讨了如何在两个已排序的数组中找到中位数的问题,并提供了一种通过合并和冒泡排序来解决该问题的方法。该方法适用于总运行时间复杂度为O(log(m+n))的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

4. Median of Two Sorted Arrays

题目描述

There are two sorted arrays nums1 and nums2 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)).

Example 1:

nums1 = [1, 3]
nums2 = [2]

The median is 2.0

Example 2:

nums1 = [1, 2]
nums2 = [3, 4]

The median is (2 + 3)/2 = 2.5

Subscribe to see which companies asked this question.

解题思路
  1. 判断两个数组size的和为奇为偶;
  2. 合并两个数组;
  3. 冒泡排序;
  4. 根据1求出的奇偶输出中间数。
    方法简单,但效率低。
代码实现
class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        int m=nums1.size();
        int n=nums2.size();
        int flag=0;
        if((m+n)%2==0) flag=1;//总个数为偶
        vector<int> nums3;//整合为一个数组
        for(int i=0; i<m; i++){
            nums3.push_back(nums1[i]);
        }
        for(int i=0; i<n; i++){
            nums3.push_back(nums2[i]);
        }
        for(int i=0; i<n+m-1; i++){//冒泡排序
            int temp=nums3[i];
            for(int j=n+m-1; j>i; j--){
                if(temp>nums3[j]){
                    nums3[i]=nums3[j];
                    nums3[j]=temp;
                    temp=nums3[i];
                }
            }
        }
        if(flag==1){//偶数
            return double((nums3[(m+n)/2]+nums3[(m+n)/2-1])/2.0);
        }
        else{//奇数
            return nums3[(m+n)/2];
        }
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值