|
| 1 | +"Leetcode- https://leetcode.com/problems/merge-sorted-array/ " |
| 2 | +''' |
| 3 | +You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively. |
| 4 | + |
| 5 | +Merge nums1 and nums2 into a single array sorted in non-decreasing order. |
| 6 | + |
| 7 | +The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n. |
| 8 | + |
| 9 | +Example 1: |
| 10 | + |
| 11 | +Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 |
| 12 | +Output: [1,2,2,3,5,6] |
| 13 | +Explanation: The arrays we are merging are [1,2,3] and [2,5,6]. |
| 14 | +The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1. |
| 15 | +''' |
| 16 | +def merge(self, nums1, m, nums2, n): |
| 17 | + i = 0 |
| 18 | + j = 0 |
| 19 | + ans = [] |
| 20 | + while j < n: |
| 21 | + ans.append(nums2[j]) |
| 22 | + j += 1 |
| 23 | + while i < m: |
| 24 | + ans.append(nums1[i]) |
| 25 | + i += 1 |
| 26 | + ans = sorted(ans) |
| 27 | + nums1[:] = ans |
0 commit comments