zoukankan      html  css  js  c++  java
  • 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
    

      

  • 相关阅读:
    画多个立方体组成的正方体
    MATLAB 图形着色
    patch函数的解释2
    patch函数的解释1
    矩阵方程求解内置函数
    Hessian矩阵
    MATLAB卷积运算(conv、conv2、convn)解释
    MATLAB常用快捷键命令总结
    稀疏矩阵绘制
    P1855 榨取kkksc03【多维01背包】
  • 原文地址:https://www.cnblogs.com/xqn2017/p/8006868.html
Copyright © 2011-2022 走看看