88. 合并两个有序数组
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
if (n == 0)
return;
int[] nums3 = new int[m + n];
int i = 0, x = 0, y = 0;
while (x < m && y < n) {
nums3[i++] = (nums1[x] <= nums2[y]) ? nums1[x++] : nums2[y++];
}
while (x < m)
nums3[i++] = nums1[x++];
while (y < n)
nums3[i++] = nums2[y++];
for (int j = 0; j < (m + n); j++) {
nums1[j] = nums3[j];
}
}
}
这道题要注意几点:
- 不能直接在原nums1上操作,因为这样会覆盖nums1还没有排序的数组。所以我准备了nums3
- 准备两个“指针”扫描完两个数组之后,还要处理nums1和nums2中没有处理完的数。