xqn2017

导航

88. Merge Sorted Array

原文题目:

 

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.

 

读题:

有两个有序整数数组nums1和nums2,将nums2合并到nums1中,根据提示已经假设了nums1有足够的空间容纳nums1和nums2的所有元素,同时nums1和nums2的长度分别为m和n

由于合并后的数组需要放入原nums1数组,为了在合并的过程中又不影响原先nums1的数据获取,因此可以从尾到前依次添加,这样nums1前面的数据才不会受到影响

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.
		"""
		p = m - 1
		q = n - 1
		k = m + n -1
		while p >= 0  and q >= 0:
			if nums1[p] >= nums2[q]:
				nums1[k] = nums1[p]
				p -= 1
				k -= 1
			else:
				nums1[k] = nums2[q]
				q -= 1
				k -= 1
		'''这里判断nums2是否还有元素,则加入到nums1中,如果nums2中没有元素了,则说明已经合并完成,不做任何处理'''
		while q >= 0: 
			nums1[k] = nums2[q]
			q -= 1
			k -= 1

  

posted on 2017-12-08 19:21  xqn2017  阅读(143)  评论(0编辑  收藏  举报