Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively.
这道题在剑指OFFER的2.3.2字符串一节中有讲道,和改变url是一个道理:例题
"we are happy" --> "we%20are%20happy" 如果从前往后遍历,那么"happy"就要被重复移动2次,所以这是O(n方)的解法
原创方法:
算法复杂度O(n),不用开辟新的存储空间
思想:
数组类题目重点在于维护index游标,
indexi指向nums1最后一个位置的游标,
indexj指向nums2最后一个位置的游标,
nums1数组和nums2数组都是从后往前遍历,
把两个数组当前最后一个位置较大的放到nums1[m+n-1],就是nums1作为新数组的最后一个位置上,
然后indexi或indexj游标相应-1
最后如果是indexj先到负数了,证明nums1还有未考虑到的数,而此时nums2的数比nums1剩余的还未考虑的数大。所以,此时新数组nums1还未填充的数就是原来nums1位置上的数。
最后如果是indexi先到负数了,证明nums2还有未考虑到的数,而此时nums1的数比nums2剩余的未考虑的数大。所以,此时新数组nums1还未填充的数就是把nums2还未考虑到的数(按顺序,nums2本来已经有序)挪过去(填充进去)。
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.
"""
indexi=m-1#指向nums1数组的最后一个位置
indexj=n-1#指向nums2数组的最后一个位置
while indexi>=0 and indexj>=0:
if nums1[indexi]>=nums2[indexj]:
nums1[indexi+indexj+1]=nums1[indexi]#indexi+indexj+1指向合并后数组的最后一个位置
indexi=indexi-1
else:
nums1[indexi+indexj+1]=nums2[indexj]
indexj=indexj-1
while indexj>=0:
nums1[indexi+indexj+1]=nums2[indexj]
indexj=indexj-1
总结思考:
与Leetcode21题混合看,21题是merge两个有序链表,思路在于改变.next指针的指向
本题array用list存储数组,重点在于维护index游标。