Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit db0e141

Browse files
committedSep 27, 2016
EASY/src/easy/MergeSortedArray.java
1 parent 6095899 commit db0e141

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
 

‎EASY/src/easy/MergeSortedArray.java

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package easy;
2+
3+
public class MergeSortedArray {
4+
5+
/**I used O(m) extra space to create a temp array, but this could be avoided.*/
6+
public static void merge(int[] nums1, int m, int[] nums2, int n) {
7+
int[] temp = new int[m];
8+
for(int i = 0; i < m; i++) temp[i] = nums1[i];
9+
for(int i = 0, j = 0, k = 0; i < m || j < n;){
10+
if(i == m){
11+
for(; j < n;){
12+
nums1[k++] = nums2[j++];
13+
}
14+
break;
15+
}
16+
if(j == n){
17+
for(; i < m;){
18+
nums1[k++] = temp[i++];
19+
}
20+
break;
21+
}
22+
23+
if(temp[i] > nums2[j]){
24+
nums1[k++] = nums2[j++];
25+
} else {
26+
nums1[k++] = temp[i++];
27+
}
28+
}
29+
}
30+
31+
public static void main(String...args){
32+
// int[] nums1 = new int[]{2,0};
33+
// int m = 1;
34+
// int[] nums2 = new int[]{1};
35+
// int n = 1;
36+
37+
int[] nums1 = new int[]{4,5,6,0,0,0};
38+
int m = 3;
39+
int[] nums2 = new int[]{1,2,3};
40+
int n = 3;
41+
merge(nums1, m, nums2, n);
42+
}
43+
}

0 commit comments

Comments
 (0)
Failed to load comments.