Last active
January 22, 2022 17:41
-
-
Save MorrisLaw/49e570017ffbf090fe8ab7a33ab9baca to your computer and use it in GitHub Desktop.
failed
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func merge(nums1 []int, m int, nums2 []int, n int) { | |
j := n-1 | |
if m == 0 { | |
for i := len(nums1)-1; i >= 0; i-- { | |
nums1[i] = nums2[j] | |
j-- | |
} | |
} | |
k := len(nums1)-1 | |
for i := m-1; i >= 0; i-- { | |
if j < 0 { | |
nums1[k] = nums1[i] | |
k-- | |
} else if nums1[i] > nums2[j] { | |
nums1[k] = nums1[i] | |
k-- | |
} else if nums1[i] < nums2[j] { | |
nums1[k] = nums2[j] | |
k-- | |
j-- | |
i++ // to maintain the current i position | |
} else if nums1[i] == nums2[j] { | |
nums1[k] = nums1[i] | |
k-- | |
} | |
} | |
if j >= 0 { | |
for k >= 0 { | |
nums1[k] = nums2[j] | |
k-- | |
j-- | |
} | |
} | |
} |
nums1.length == m + n
Implies that the length is 1 if m==0 because we must have a spot for num2's number, then n must be 1. Right?
There's also this example:
Input: nums1 = [0], m = 0, nums2 = [1], n = 1
Output: [1]
Explanation: The arrays we are merging are [] and [1].
The result of the merge is [1].
Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1.
But maybe I'm misreading this @CollinShoop
Ahh I see what you're saying. For example n could be 5 and m 0..
fixed now
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
1, Line 2:
m == 0
does not implyn==1
2. What happens if j >= 0 after the main loop?