4. Median of Two Sorted Arrays
来源:互联网 发布:淘宝网京东商城茅台酒 编辑:程序博客网 时间:2024/06/06 03:30
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
过了
O(M+N)
应该是够的
----------------------
不过 有问题
即使
现在写出来
写一会儿之后
还是感觉
自己没法
下次很快写出来
逻辑还是很乱的
不清晰
这是为啥呢?
而且这个简单题
也花了1个小时
。
----------------------
如果复杂度不够,再说吧
-----------------------------
//4.cpp
//log m+n
//里面的排序 数据结构学了很多
//排序算法 -> 堆排序
//两个已经排序好了的 应该很简单才对吧
//中间逻辑有点晕乎了
//重新来
//怎么搞呢
------------
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int i=0,j=0;
int l=nums1.size()+nums2.size();
int aim,aim1,aim2,flag2;
bool flag1;
double out,out1,out2;
if(l%2==1){
aim=l/2;
flag1=true;
}
else{
aim1=l/2-1;
aim2=l/2;
flag1=false;
}
int p1=0,p2=0,count=-1;
for(i=0;i<l;i++){
count++;
if(p1==nums1.size()){
p2++;
flag2=2;
}
else if(p2==nums2.size()){
p1++;
flag2=1;
}
else if(nums1[p1]<nums2[p2]){
p1++;
flag2=1;
}
else{
p2++;
flag2=2;
}
//judge
if(flag1){
if(count==aim){
if(flag2==1)
out=(double)nums1[p1-1];
else
out=(double)nums2[p2-1];
}
}
else{
if(count==aim1){
if(flag2==1)
out1=(double)nums1[p1-1];
else
out1=(double)nums2[p2-1];
}
if(count==aim2){
if(flag2==1)
out2=(double)nums1[p1-1];
else
out2=(double)nums2[p2-1];
}
}
if(flag1&&count==aim)
break;
if(!flag1&&count==aim2){
out=(out1+out2)/2;
break;
}
}
//cout<<out<<endl;
return out;
}
};
int main(){
vector<int> a,b;
a.push_back(1);
a.push_back(2);
b.push_back(3);
b.push_back(4);
Solution c;
cout<<c.findMedianSortedArrays(b,a)<<endl;
}
- [LeetCode]4.Median of Two Sorted Arrays
- LeetCode 4. Median of Two Sorted Arrays
- LeetCode --- 4. Median of Two Sorted Arrays
- [Leetcode] 4. Median of Two Sorted Arrays
- 4.Median of Two Sorted Arrays
- [LeetCode]4.Median of Two Sorted Arrays
- 4. Median of Two Sorted Arrays
- 4.Median of Two Sorted Arrays
- 4. Median of Two Sorted Arrays
- 4. Median of Two Sorted Arrays
- 【leetcode】4. Median of Two Sorted Arrays
- Leetcode-4.Median of Two Sorted Arrays
- 4. Median of Two Sorted Arrays
- 4. Median of Two Sorted Arrays
- LeetCode-4.Median of Two Sorted Arrays
- leetcoode 4. Median of Two Sorted Arrays
- Leetcode 4. Median of Two Sorted Arrays
- leetcode 4. Median of Two Sorted Arrays
- java基础.集合.properties.初识
- Android5 Lollipop 中关于 SELinux 安全机制调试笔记
- 访问maven项目总是报404
- Android杂谈(21)补坑+Path动画
- selenium+testng+gitblit+jenkins+ant自动化测试系列六:eclipse上传代码到服务器
- 4. Median of Two Sorted Arrays
- java自带工具keytool生成keystore
- JavaIO输入输出流的总结
- eclipse jni 编译第三方.a文件报错
- 页面制作之调试工具
- 洛谷 P1273 有线电视网
- 响应式编程在Android中的应用
- IOS
- sqlite3命令