88.Merge Sorted Array
Tags: [sort], [merge], [in_place]
Com: {fb}
Link: https://leetcode.com/problems/merge-sorted-array/#/description
Given two sorted integer arraysnums1andnums2, mergenums2intonums1as one sorted array.
Note:
You may assume that nums1 has enough space (size that is greater or equal tom+n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively.
Better Solution: In Place
class Solution(object):
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-place instead.
"""
index1 = m - 1
index2 = n - 1
main_index = m + n - 1
while index1 >= 0 and index2 >= 0:
n1 = nums1[index1]
n2 = nums2[index2]
if n1 == n2:
nums1[main_index] = n1
nums1[main_index - 1] = n2
main_index -= 2
index1 -= 1
index2 -= 1
elif n1 < n2:
nums1[main_index] = n2
main_index -= 1
index2 -= 1
else:
nums1[main_index] = n1
main_index -= 1
index1 -= 1
while index2 >= 0:
nums1[main_index] = nums2[index2]
main_index -= 1
index2 -= 1
Revelation:
- Scan the nums1 and nums2 from right side to left side, to make use of the space of nums1.
- Don't forget to check the following part after the main while loop.
while index2 >= 0:
nums1[main_index] = nums2[index2]
main_index -= 1
index2 -= 1
Note:
- Time complexity = O(n), n is the number of elements of the given array.
- Space complexity = O(1).
Solution:
class Solution(object):
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-place instead.
"""
result = []
index_1 = 0
index_2 = 0
while index_1 < m and index_2 < n:
n1 = nums1[index_1]
n2 = nums2[index_2]
if n1 == n2:
result.append(n1)
result.append(n2)
index_1 += 1
index_2 += 1
elif n1 < n2:
result.append(n1)
index_1 += 1
else:
result.append(n2)
index_2 += 1
result += nums1[index_1:m]
result += nums2[index_2:n]
for i in xrange(len(result)):
nums1[i] = result[i]
Note:
- Time complexity = O(m + n).
- Space complexity = O(m + n).