标签:
#include<iostream> #include<vector> using namespace std; class Solution { public: double findMedianSortedArrays(int A[], int m, int B[], int n) { int findNum=0; if((m+n)%2==0) findNum=2; else findNum=1; int leftOffsetA=0,leftOffsetB=0; int rightOffsetA=0,rightOffsetB=0; while(leftOffsetA+leftOffsetB+rightOffsetA+rightOffsetB!=m+n-findNum) { if(leftOffsetA==m|| rightOffsetA==m) { //左右端都在B中 int halfLenthOfPartB=(n-1-leftOffsetB-rightOffsetB)/2; leftOffsetB+=halfLenthOfPartB; rightOffsetB+=halfLenthOfPartB; break; } else if(leftOffsetB==n|| rightOffsetB==n) { //左右端都在A中 int halfLenthOfPartA=(m-1-leftOffsetA-rightOffsetA)/2; leftOffsetA+=halfLenthOfPartA; rightOffsetA+=halfLenthOfPartA; break; } else { //左端还分别在A、B中 if(A[leftOffsetA]<B[leftOffsetB]) leftOffsetA++; else leftOffsetB++; if(A[m-1-rightOffsetA]>B[n-1-rightOffsetB]) rightOffsetA++; else rightOffsetB++; } } // cout<<"leftOffsetA:"<<leftOffsetA<<" rightOffsetA"<<rightOffsetA<<endl; // cout<<"leftOffsetB:"<<leftOffsetB<<" rightOffsetB"<<rightOffsetB<<endl; //取出两段截断的int数据 vector<int> ivec; for(int index_i=leftOffsetA;index_i<=m-1-rightOffsetA &&index_i<m;index_i++) { ivec.push_back(A[index_i]); //cout<<"A中取出:"<<A[index_i]<<endl; } for(int index_i=leftOffsetB;index_i<=n-1-rightOffsetB &&index_i<n;index_i++) { ivec.push_back(B[index_i]); //cout<<"B中取出:"<<B[index_i]<<endl; } if(findNum==1) return ivec[0]; else return (ivec[0]+ivec[1])/2.0f; } };
LeetCode 2.Median of Two Sorted Arrays
标签:
原文地址:http://www.cnblogs.com/kyokuhuang/p/4190249.html