Skip to content

Instantly share code, notes, and snippets.

@charlespunk
Created October 15, 2013 01:28
Show Gist options
  • Save charlespunk/6985182 to your computer and use it in GitHub Desktop.
Save charlespunk/6985182 to your computer and use it in GitHub Desktop.
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.
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