Topic links
https://leetcode.com/problems/merge-sorted-array/
Original title
Given sorted integer Arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
Assume that nums1 have enough space (size that's greater or equal to M + N) to hold additional elements from NUMS2 . The number of elements initialized in Nums1 and Nums2 is M and N respectively.
Topic translation
Given two ordered integer arrays nums1 and nums2, merge nums2 into Nums1 to get an ordered array.
Note: Assume that the nums1 has enough space (whose size is greater than or equal to m+n) to hold the NUMS2 element. Nums1 and Nums2 initially have m and n elements respectively.
Method of Thinking
Idea one
Now that you want to merge into Nums1, start with the trailing elements of the merged nums1, and in turn determine how much each element should be. The program needs to use three pointers.
Code
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 does not return anything, modify NUMS1 in-place instead. """P, q, k = m1, N-1, m+n-1 whileP >=0 andQ >=0:ifNUMS1[P] > Nums2[q]: nums1[k] = Nums1[p] p, k = P1, K-1 Else: nums1[k] = nums2[q] Q, k = q1, K-1nums1[:q+1] = nums2[:q+1]
Idea two
With a small trick, use only two pointers.
Code
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 does not return anything, modify NUMS1 in-place instead. """P, q = m1, N-1 whileP >=0 andQ >=0:ifNUMS1[P] > Nums2[q]: nums1[p+q+1] = nums1[p] p = P1 Else: nums1[p+q+1] = nums2[q] Q = q1nums1[:q+1] = nums2[:q+1]
PS: Novice Brush Leetcode, new handwritten blog, write wrong or write not clear also please help point out, thank you!
Reprint Please specify: http://blog.csdn.net/coder_orz/article/details/51681144
A. Merge Sorted Array [Easy] (Python)