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
【leetcode|leetcode_4】一看到这个题目,就想到了合并归序,就是两部分相加的部分,找到中间两位数即可返回
class Solution {
public:
double findMedianSortedArrays(vector& nums1, vector& nums2) {
int i = 0,j=0,k=0;
int m = nums1.size();
int n = nums2.size();
int num[n+m];
while(i < m && j < n) {
if(nums1[i]<=nums2[j])
num[k++]=nums1[i++];
else
num[k++]=nums2[j++];
if(k==(n+m)/2+1)
return (double(num[(m+n)/2]+num[(m+n-1)/2])/2.0);
}
while (i < m) {
num[k++]=nums1[i++];
if(k==(n+m)/2+1)
return (double(num[(m+n)/2]+num[(m+n-1)/2])/2.0);
}
while (j < n) {
num[k++]=nums2[j++];
if(k==(n+m)/2+1)
return (double(num[(m+n)/2]+num[(m+n-1)/2])/2.0);
}
}
};
推荐阅读
- 数据结构与算法|【算法】力扣第 266场周赛
- leetcode|今天开始记录自己的力扣之路
- Python|Python 每日一练 二分查找 搜索旋转排序数组 详解
- 【LeetCode】28.实现strstr() (KMP超详细讲解,sunday解法等五种方法,java实现)
- LeetCode-35-搜索插入位置-C语言
- leetcode python28.实现strStr()35. 搜索插入位置
- Leetcode Permutation I & II
- python|leetcode Longest Substring with At Most Two Distinct Characters 滑动窗口法
- LeetCode 28 Implement strStr() (C,C++,Java,Python)
- Python|Python Leetcode(665.非递减数列)