Merge Sorted Array
Given sorted integer arrays A and B, merge B into a as one sorted array.
Has you met this question in a real interview?YesWhich company asked do you question?AirbnbAlibabaAmazonAppleBaiduBloombergCiscoDropboxEbayFacebook Google Hulu Intel Linkedin Microsoft NetEase Nvidia Oracle Pinterest Snapchat Tencent Twitter Uber Xiaomi Yahoo Yelp Zenefits
Thanks for your feedback.
Example
A = [1, 2, 3, empty, empty]
, B =[4, 5]
After merge, A'll be filled as[1, 2, 3, 4, 5]
Note
You could assume that A have enough space (size that's greater or equal to m + n) to the hold additional Eleme NTS from B. The number of elements initialized in A and B is m and n respectively.
Because It is sorted array, we can compare them from the end to the start.
Which one is greater, put it in the last array A
Keep decreasing M and n
Until M or n equal to 0
If m=0, copy all of the numbers in array B to A;
classSolution {/** * @parama:sorted Integer array A which have m elements, * but size of a is m+n *@paramb:sorted integer array B which has n elements *@return: void*/ Public voidMergesortedarray (int[] A,intMint[] B,intN) {//Write your code here while(m>0&&n>0) { if(a[m-1]>b[n-1]) {a[m+n-1]=a[m-1]; M--; } Else{a[m+n-1]=b[n-1]; N--; } } while(n>0) {a[m+n-1]=b[n-1]; N--; } }}
[Lintcode Easy] Merge Sorted Array