Leetcode 4:Median of Two Sorted Arrays(寻找两个有序数组的中位数)

Description

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)). You may assume nums1 and nums2 cannot be both empty.

给定两个大小为 m 和 n 的有序数组 nums1 和 nums2。请你找出这两个有序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。你可以假设 nums1 和 nums2 不会同时为空。

Example

Input:
	nums1 = [1, 3]
	nums2 = [2]
Output:
	The median is 2.0


Input:
	nums1 = [1, 2]
	nums2 = [3, 4]
Output:
	The median is (2 + 3)/2 = 2.5

My Solution

直接将一个vector插到另一个后面,再排序取中值(全程调用系统函数。。)。

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2)
{
	for (size_t i = 0; i < nums1.size(); i++)
		nums2.push_back(nums1[i]);

	sort(nums2.begin(), nums2.end());

	if (nums2.size() % 2 == 0)
		return (nums2[nums2.size() / 2] + nums2[nums2.size() / 2 - 1]) / 2.0;
	else
		return nums2[(nums2.size() - 1) / 2] * 1.0;
}

int main(void)
{
	vector<int> v1 = {4, 5, 1};
	vector<int> v2 = {1, 2};
	cout << findMedianSortedArrays(v1, v2) << endl;
}

wayne17

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值