Created
October 15, 2013 01:28
-
-
Save charlespunk/6985182 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Given two sorted integer arrays A and B, merge B into A as one sorted array. | |
Note: | |
You may assume that A has enough space to hold additional elements from B. The number of elements initialized in A and B are m and n respectively. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Solution { | |
public void merge(int A[], int m, int B[], int n) { | |
// Note: The Solution object is instantiated only once and is reused by each test case. | |
int aPos = m - 1; | |
int bPos = n - 1; | |
int mergePos = A.length - 1; | |
while(aPos >= 0 && bPos >= 0){ | |
if(A[aPos] >= B[bPos]){ | |
A[mergePos] = A[aPos]; | |
aPos--; | |
mergePos--; | |
} | |
else{ | |
A[mergePos] = B[bPos]; | |
bPos--; | |
mergePos--; | |
} | |
} | |
while(bPos >= 0){ | |
A[mergePos] = B[bPos]; | |
bPos--; | |
mergePos--; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment