Created
April 29, 2013 00:56
-
-
Save daifu/5479095 to your computer and use it in GitHub Desktop.
Merge Sorted Array
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
/* | |
Merged two sorted array. | |
merged B into A | |
*/ | |
public class Solution { | |
public void merge(int A[], int m, int B[], int n) { | |
// Start typing your Java solution below | |
// DO NOT write main() function | |
if(n == 0) return; | |
ArrayList<Integer> list = new ArrayList<Integer>(); | |
int a = 0; | |
int b = 0; | |
while(a < m || b < n) { | |
if(a == m) { | |
list.add(B[b]); | |
b++; | |
continue; | |
} | |
if(b == n) { | |
list.add(A[a]); | |
a++; | |
continue; | |
} | |
if(A[a] < B[b]) { | |
list.add(A[a]); | |
a++; | |
} else if(A[a] > B[b]) { | |
list.add(B[b]); | |
b++; | |
} else { | |
list.add(A[a]); | |
list.add(B[b]); | |
a++; | |
b++; | |
} | |
} | |
for(int i = 0; i < list.size(); i++) { | |
A[i] = list.get(i); | |
} | |
return; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment