【LEETCODE】88-Merge Sorted Array

来源:互联网 发布:大数据培训视频 编辑:程序博客网 时间:2024/05/20 17:40

Given two sorted integer arrays nums1 andnums2, merge nums2 into nums1 as 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 innums1 and nums2 are m and n respectively.


参考:

http://m.blog.csdn.net/blog/fox64194167/20733349

http://www.cnblogs.com/zuoyuan/p/3769714.html


题意:

两个有序数组,合并成一个有序数组,其中 nums1 足够长,可以直接对 nums1 in place 操作


思路:

两个指示器,分别指向两个数组的最后一个数

比较指示器所指示的数的大小,较大的数字放在nums1的尾部,从第m+n个位置向前放

较大的数的指示器向前一步,

继续比较

当nums2先放完后,直接得到新的nums1

当nums1先放完后,将剩余的nums2放到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.        """                i=m-1        j=n-1        k=m+n-1                while i>=0 and j>=0:            if nums1[i]>nums2[j]:            #将两个数组中较大的数字放在nums1的第k个位置上                nums1[k]=nums1[i]                i-=1                #k-=1            else:                nums1[k]=nums2[j]                j-=1                #k-=1            k-=1                if i<0 and j>=0:                     #如nums1已经比较完毕,nums2还有剩余,则全部放进nums1的前端            while j>=0:                nums1[j]=nums2[j]                j-=1                #return nums1       #Do not return anything, modify nums1 in-place instead.


0 0
原创粉丝点击