LeetCode--4. 寻找两个有序数组的中位数(Median of Two Sorted Arrays)
2019-03-09 13:35
561 查看
题目描述
给定两个大小为 m 和 n 的有序数组 nums1 和 nums2。
请你找出这两个有序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。
你可以假设 nums1 和 nums2 不会同时为空。
示例 1:
nums1 = [1, 3] nums2 = [2] 则中位数是 2.0
示例 2:
nums1 = [1, 2] nums2 = [3, 4] 则中位数是 (2 + 3)/2 = 2.5
思路
class Solution { public: double findMedianSortedArrays(vector<int> num1, vector<int> num2) { int m=num1.size(); int n=num2.size(); double ans; if(m>n) {//确保要从个数少的数组里划分,否则会造成越界 vector<int> temp(num1); num1.swap(num2); num2.swap(temp); int tempp=m; m=n; n=tempp; } int imin=0,imax=m,halfl=(m+n+1)/2; //i为划分的位置,取值为0-m,halfl为总体小的分组,且个数跟大的分组相等,或多1个 while(imin<=imax) { int i=(imin+imax)/2; int j=halfl-i; if(i<imax&&num1[i]<num2[j-1]) imin=i+1; //i需要再大点 else if(i>imin&&num1[i-1]>num2[j]) imax=i-1; //i需要再小点 else {//i已经达到要求 int ansl=0; if(i==0)//说明num1数组在小数组部分没有数,故小数组最大值在num2中找 ansl=num2[j-1]; else if(j==0)//同上 ansl=num1[i-1]; else //说明num1和num2在小数组中都有数,所以取两个中较大的数 ansl=num1[i-1]>num2[j-1]?num1[i-1]:num2[j-1]; if((n+m)&1) { ans=ansl; break; } int ansr=0; //说明num1数组的所有数都在小数组中 //故大数组最小值只能在num2中 if(i==m) ansr=num2[j]; else if(j==n)//同 ansr=num1[i]; else ansr=num1[i]<num2[j]?num1[i]:num2[j]; ans=(ansl+ansr)/2.0; break; } } return ans; } };
相关文章推荐
- [leetcode] Median of Two Sorted Arrays 寻找两个有序数组的中位数
- [LeetCode]Median of Two Sorted Arrays 二分查找两个有序数组的第k数(中位数)
- Median of Two Sorted Arrays 两个有序数组的中位数@LeetCode
- Median of Two Sorted Arrays - 寻找两个有序数组的中位数(重)
- [LeetCode] Median of Two Sorted Arrays 两个有序数组的中位数
- [LeetCode] Median of Two Sorted Arrays 两个有序数组的中位数
- ~~~~(>_<)~~~~Median of Two Sorted Arrays:两个有序数组寻找中位数
- [LeetCode]Median of Two Sorted Arrays 二分查找两个有序数组的第k数(中位数)
- [LeetCode] Median of Two Sorted Arrays 两个有序数组的中位数
- Median of Two Sorted Arrays 两个有序数组的中位数@LeetCode
- [Leetcode #4]Median of Two Sorted Arrays 计算两个有序数组的中位数
- LeetCode-Median of Two Sorted Arrays,找出两个排好序的数组的中位数
- LeetCode OJ 之 Median of Two Sorted Arrays(两个有序数组的中位数)
- Q4 Median of Two Sorted Arrays 两个有序数组的中位数
- Median of Two Sorted Arrays---两个有序数组查找中位数
- [LintCode] Median of Two Sorted Arrays 两个有序数组的中位数
- 【LeetCode】004 Median of Two Sorted Arrays 两个排序数组合并后的中位数
- Median of Two Sorted Arrays(两个有序数组的中位数)
- 寻找两个数组的中位数 Median of Two Sorted Arrays ***问题转化思想***
- 【LeetCode-面试算法经典-Java实现】【004-Median of Two Sorted Arrays(两个排序数组的中位数)】