mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
Create 88. Merge Sorted Array.md
This commit is contained in:
parent
2e1db50ece
commit
cecc32ec97
21
88. Merge Sorted Array.md
Normal file
21
88. Merge Sorted Array.md
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
# [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对应的位置
|
||||||
|
}
|
||||||
|
};
|
||||||
|
```
|
Loading…
Reference in New Issue
Block a user