p88

LeetCode 88 Merge Sorted Array 题解

1.题目:

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively.
Subscribe to see which companies asked this question

题意:

输入两个有序数组,将他们合并排序

2.解题思路:

插入排序.

3.代码


[title] [] [url] [link text]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
 

public class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
if (n == 0)
return;
if (m == 0) {
for (int i = 0; i < n; i++) {
nums1[i] = nums2[i];
}

return;
}
int[] nums3 = new int[m + n];

int a = 0;
int b = 0;
for (int i = 0; i < n + m; i++) {

if (nums1[a] < nums2[b]) {
if (a <= m - 1) {
nums3[i] = nums1[a];
a++;
}

if (a > m - 1) {
while (b < n) {
nums3[++i] = nums2[b];
// System.out.println(" "+i+" "+b+" "+a);
b++;

}
break;
}
} else {
if (b <= n - 1) {
nums3[i] = nums2[b];
b++;
}

if (b > n - 1) {
while (a < m) {
nums3[++i] = nums1[a];
// System.out.println(" "+i+" "+b+" "+a);
a++;

}
break;
}
}

}
for (int i = 0; i < m + n; i++) {
nums1[i] = nums3[i];
}
}
}


4.一些总结: