88. Merge Sorted Array
Question:
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. Note:
- The number of elements initialized in nums1 and nums2 are m and n respectively.
- You may assume that nums1 has enough space (size that is equal to m + n) to hold additional elements from nums2.
Example
Input:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
Source code
Version 1
Idea:
My initial approach is to use queue to store element. The processing of merging is in order, I compare witch each elements, if the element is smaller, it will be assign to nums1[i] after the original value of index i will push to queue at nums vector. But, I faced many if statement in my code, it's too complicated.
Finally, I refered to ChingYuanYang, I gained an impressive solution after realizing his explanation.
I can assign the element from the last position in reverse order at nums1 vector that is the largest value. It's an easy way to merge vectors.
Time complexity: O(m + n)
Space complexity: O(1)
1 | class Solution { |
Version 2
Idea:
It's a perfert code from Huahua's Tech Road.
According to the question, it says "merge nums2 into nums1", so we can use the size (=n) of nums2 as while statement rather than the size (=m+n) of nums1. Then, use only one statement to implement clean code with no if statement.
Time complexity: O(m + n)
Space complexity: O(1)
1 | class Solution { |