88. Merge Sorted Array
LeetCode 88. Merge Sorted Array
Description
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
The number of elements initialized in nums1 and nums2 are m and n respectively. You may assume that nums1 has a size equal to m + n such that it has enough space to hold additional elements from nums2.
Example 1:
Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]Example 2:
Input: nums1 = [1], m = 1, nums2 = [], n = 0
Output: [1]Constraints:
nums1.length == m + nnums2.length == n0 <= m, n <= 2001 <= m + n <= 200-109 <= nums1[i], nums2[i] <= 109
Tags
Array, Two Pointers
Solution
Use two pointers i, j start from m - 1 at nums1 and n - 1 at nums2 respectively, and another pointer k is assigned to the last position of nums1. Compare nums1[i] and nums2[j] until one of both pointers is out of index. We move the larger one to the slot which k points to, and decrease k and the pointer of the larger one by 1 respectively. After this loop, we still need to check if there are remaining numbers in nums2 (we do not need to check nums1 because elements of nums1 are already in their place). We repeatedly assign nums2[j] to nums1[k] until j is out of index.
Complexity
Time complexity:
Space complexity:
Code
Last updated
Was this helpful?