def merge(self, nums1, m, nums2, n): while m > 0 and n > 0: if nums1[m-1] >= nums2[n-1]: nums1[m+n-1] = nums1[m-1] m -= 1 else: nums1[m+n-1] = nums2[n-1] n -= 1 if n > 0: nums1[:n] = nums2[:n]
A solution may be more concise:
def merge(self, nums1, m, nums2, n): while n > 0: if m <= 0 or nums2[n-1] >= nums1[m-1]: nums1[m+n-1] = nums2[n-1] n -= 1 else: nums1[m+n-1] = nums1[m-1] m -= 1
My custom test case is :
And I got error:IndexError: list assignment index out of range.
Do you know why?
Because your custom test case is wrong. The first list should have enough space for merging two lists. So you can try:
The last "0" is the extra space for merging. Anyway, the description of the problem is not clear. I had tried several test cases to figure it out.
@cffls this is indeed a beautiful solution!
@tju_xu97 This is great. The use of OR operator helps escape the out of index range error which busted my mind for hours. Thanks a lot.
def merge(self, nums1, m, nums2, n):
while n > 0:
if m <= 0 or nums2[n-1] >= nums1[m-1]:
nums1[m+n-1] = nums2[n-1]
n -= 1
nums1[m+n-1] = nums1[m-1]
m -= 1
Why this is not working for the following ??
why this code give me a ''wrong answer''??? I don't understand.
for i in range(n):
If I change the last line into nums1 = nums[:n]
the answer is wrong.
input:, 0, , 1
But run the code in my pc that the output is .
don't konw the reason.
Input: 0  1
This is a wrong testcase,the length of  should be 1 not 0.
It should be  0  1 or  1  1
@cffls This is certainly an elegant solution :) Thank you for sharing!
What if the input nums1 and nums2 are descending? Looks like it can't deal with this.
For the input below, the result is [1,3,2,1,2], which is wrong. The expected answer [3,2,1,1,2] is also wrong.
[3, 2, 1, 0, 0]
This is way easier(beats 98.5%)...
def merge(self, nums1, m, nums2, n): nums1[m:] = nums2[:n] nums1.sort()
Also, I believe some of you are reading the question wrong. We only use the first m numbers in nums1 and the first n numbers in nums2 for the final solution.
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.