Skip to content

Instantly share code, notes, and snippets.

@MorrisLaw
Last active January 22, 2022 17:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MorrisLaw/49e570017ffbf090fe8ab7a33ab9baca to your computer and use it in GitHub Desktop.
Save MorrisLaw/49e570017ffbf090fe8ab7a33ab9baca to your computer and use it in GitHub Desktop.
failed
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--
}
}
}
@CollinShoop
Copy link

1, Line 2: m == 0 does not imply n==1
2. What happens if j >= 0 after the main loop?

@MorrisLaw
Copy link
Author

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

@MorrisLaw
Copy link
Author

MorrisLaw commented Jan 22, 2022

Ahh I see what you're saying. For example n could be 5 and m 0..

@MorrisLaw
Copy link
Author

fixed now

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment