|
| 1 | +# https://leetcode.com/explore/learn/card/fun-with-arrays/525/inserting-items-into-an-array/3253/ |
| 2 | + |
| 3 | +# Test cases: |
| 4 | +# nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 |
| 5 | +# nums1 = [1], m = 1, nums2 = [], n = 0 |
| 6 | +# nums1 = [0], m = 0, nums2 = [1], n = 1 |
| 7 | +# nums1 = [2,0], m = 1, nums2 = [1], n = 1 |
| 8 | +# nums1 = [-1,0,0,3,3,3,0,0,0], m = 6, nums2 = [1,2,2], n = 3 |
| 9 | + |
| 10 | +# Expected results: |
| 11 | +# [1,2,2,3,5,6] |
| 12 | +# [1] |
| 13 | +# [1] |
| 14 | +# [1,2] |
| 15 | +# [-1,0,0,1,2,2,3,3,3] |
| 16 | + |
| 17 | +# @param {Integer[]} nums1 |
| 18 | +# @param {Integer} m |
| 19 | +# @param {Integer[]} nums2 |
| 20 | +# @param {Integer} n |
| 21 | +# @return {Void} Do not return anything, modify nums1 in-place instead. |
| 22 | +def merge(nums1, m, nums2, n) |
| 23 | + # Return nums1 of nums2 is empty |
| 24 | + return nums1 if n.zero? |
| 25 | + |
| 26 | + length = m + n |
| 27 | + |
| 28 | + 0.upto(length - 1) do |i| |
| 29 | + # If nums2 is empty, then there is only elements of nums1 left |
| 30 | + next if nums2.empty? |
| 31 | + |
| 32 | + # If there is no elements left in nums1, then just copy all other elements from nums2 to nums1 |
| 33 | + if m.zero? |
| 34 | + e = nums2.shift |
| 35 | + nums1[i] = e |
| 36 | + # If element from nums1 is bigger then element from nums2, then shift all elements in nums1 to the right |
| 37 | + elsif nums1[i] > nums2[0] |
| 38 | + e = nums2.shift |
| 39 | + nums1[i + 1..length - 1] = nums1[i..length - 2] |
| 40 | + nums1[i] = e |
| 41 | + # If element from nums1 is smaller or equal then element from nums2, then jump to the next element |
| 42 | + else |
| 43 | + m -= 1 |
| 44 | + next |
| 45 | + end |
| 46 | + end |
| 47 | +end |
0 commit comments