Skip to content

Commit 6279ef0

Browse files
committed
merge two sorted array
0 parents  commit 6279ef0

2 files changed

Lines changed: 44 additions & 0 deletions

File tree

merge_two_sorted_array/readme.md

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
6. Merge Two Sorted Arrays
2+
3+
Merge two given sorted ascending integer array A and B into a new sorted integer array.
4+
5+
Example
6+
Example 1:
7+
8+
Input: A=[1], B=[1]
9+
Output: [1,1]
10+
Explanation: return array merged.
11+
Example 2:
12+
13+
Input: A=[1,2,3,4], B=[2,4,5,6]
14+
Output: [1,2,2,3,4,4,5,6]
15+
Explanation: return array merged.
16+
Challenge
17+
How can you optimize your algorithm if one array is very large and the other is very small?
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
public class Solution {
2+
/**
3+
* @param A: sorted integer array A
4+
* @param B: sorted integer array B
5+
* @return: A new sorted integer array
6+
*/
7+
public int[] mergeSortedArray(int[] A, int[] B) {
8+
int []C = new int[A.length + B.length];
9+
int i = 0;
10+
int j = 0;
11+
int indexOfc = 0;
12+
while( i < A.length && j < B.length){
13+
C[indexOfc++] = (A[i] < B[j])?A[i++]:B[j++];
14+
}
15+
16+
while( i < A.length){
17+
C[indexOfc++] = A[i++];
18+
}
19+
20+
while( j < B.length){
21+
C[indexOfc++] = B[j++];
22+
}
23+
24+
// write your code here
25+
return C;
26+
}
27+
}

0 commit comments

Comments
 (0)