LeetCode/solutions/88. Merge Sorted Array.md

22 lines
1.2 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [88. Merge Sorted Array](https://leetcode.com/problems/merge-sorted-array/description/)
# 思路
题意就是将两个已经有序的数组merge成一个有序的数组最好想的思路就是开辟一个新的数组但是能不能不用额外空间的呢
注意nums1的空间是足够容下两个数组的所以考虑用nums1而不用开辟新数组
为了不让已排好的数不覆盖掉未排好的数,我们需要从后往前遍历:
最大的数放在nums1[n+m-1],次大的数放在nums1[n+m-2],以此类推直到其中一个数组遍历结束然后将未遍历的部分依次复制到nums1即可。
所以当nums1先遍历完成时将nums2剩余的数依次复制到nums1对应的位置即可当nums2先遍历完成时不用做任何操作。
# C++
```
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
int i1 = m - 1, i2 = n - 1, j = m + n - 1;
while(i1 >= 0 && i2 >= 0){
if(nums1[i1] > nums2[i2]) nums1[j--] = nums1[i1--];
else nums1[j--] = nums2[i2--];
}
for(; i2 >= 0; i2--) nums1[j--] = nums2[i2]; // nums2剩余的数依次复制到nums1对应的位置
}
};
```