题目链接点我
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.
Solution
类似归并排序中的归并过程,题目数据有些坑爹,难怪赞/踩比例 = 162:650……
code
C++
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
// m = 0的时候默认nums1有一个0
for(int i=0;i<m+n-nums1.size();i++)
nums1.push_back(0);
int k = n + m - 1;
int it1 = m-1, it2 = n-1;
while(it1>=0 && it2>=0)
{
if(nums1[it1] >= nums2[it2])
{
nums1[k--] = nums1[it1];
it1--;
}
else
{
nums1[k--] = nums2[it2];
it2--;
}
}
//while(it1 >= 0)
//nums1[k--] = nums1[it1--];
while(it2 >= 0)
nums1[k--] = nums2[it2--];
}
};
Python
class Solution(object):
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-place instead.
"""
if m == 0: #如过不是这样删,直接用nums1 = []的话,返回值还是原来的nums1
it = len(nums1)-1
while it >= 0:
del nums1[it]
it -= 1
else:
it = len(nums1) - 1
while it >= m:
del nums1[it]
it -= 1
for i in range(n):
nums1.append(nums2[i])
nums1.sort()
print(nums1)
#return nums1