LeetCode: Merge Sorted Array Solution
1// O(m * n)2var merge = function (nums1, m, nums2, n) {3 let i = m4 while (nums2.length) {5 let el = nums2.shift()6 nums1[i] = el7 let j = i8 while (true) {9 if (nums1[j] < nums1[j - 1]) {10 ;[nums1[j], nums1[j - 1]] = [nums1[j - 1], nums1[j]]11 j--12 continue13 }14 break15 }16 i++17 }18}1920// O(m + n)21var merge = function (nums1, m, nums2, n) {22 let i = m + n - 123 m--24 n--25 while (m >= 0 && n >= 0) {26 if (nums1[m] > nums2[n]) {27 nums1[i--] = nums1[m--]28 } else {29 nums1[i--] = nums2[n--]30 }31 }32 while (n >= 0) {33 nums1[i--] = nums2[n--]34 }35}
Comments
Loading comments...
Tags
leetcode
array
two pointers
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.
Next Post
LeetCode: Set Matrix Zeroes
Feb 8, 2021
Previous Post
LeetCode: 3sum
Feb 7, 2021