Title Source: http://www.lintcode.com/zh-cn/problem/merge-sorted-array/
C + + version VS2012 Test passed
1 //#include <iostream>2 //#include <vector>3 //using namespace std;4 5 classSolution {6 Public:7 /**8 * @param a:sorted integer array A which has m elements,9 * But the size of A is M+nTen * @param b:sorted integer array B which has n elements One * @return: void A */ - voidMergesortedarray (intA[],intMintB[],intN) { - //Write your code here thevector<int>v; - intI=0, j=0, k=0; - while(I<m && j<N) - { + if(a[i]<B[j]) -V.push_back (a[i++]); + Else AV.push_back (b[j++]); at } - while(i<m) -V.push_back (a[i++]); - while(j<N) -V.push_back (b[j++]); -vector<int>:: iterator it; in for(It=v.begin (); It<v.end (); it++) -a[k++]=*it; to } + }; - the //Test * //int main () $ //{Panax Notoginseng //solution S; - // the //int a[5]={1,2,4}; + //int b[2]={3,5}; A //S.mergesortedarray (a,3,b,2); the //for (int i=0;i<5;i++) + //cout<<a[i]<< ""; - //}
Python2.7 version of Spider test passed
1 classSolution:2 """3 @param a:sorted integer array A which has m elements,4 But the size of A is M+n5 @param b:sorted integer array B which has n elements6 @return: void7 """8 defMergesortedarray (self, A, M, B, N):9 #Write your code hereTenI, j, index = M-1, n-1, M + n-1 One whileI >= 0 andJ >=0: A ifA[i] >B[j]: -A[index] =A[i] -Index, i = index-1, i-1 the Else: -A[index] =B[j] -Index, j = index-1, j-1 - whileI >=0: +A[index] =A[i] -Index, i = index-1, i-1 + whileJ >=0: AA[index] =B[j] atIndex, j = index-1, j-1 - - #Test - #if __name__== "__main__": - #s=solution () - #a=[1,2,4,0,0] in #b=[3,5] - #S.mergesortedarray (a,3,b,2)
[Easy] Merge sorted array II