leetcode88 merge sorted array

来源:互联网 发布:linux 百度网盘 编辑:程序博客网 时间:2024/05/18 15:04
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.
        """
        if not nums1:
            return 
        i=m+n-1
        a=m-1
        b=n-1
        while  a>=0 and b>=0:
            if nums1[a]>nums2[b]:
                nums1[i]=nums1[a]
                i-=1
                a-=1
            else:
                nums1[i]=nums2[b]
                b-=1
                i-=1
        while b>=0:
            nums1[i]=nums2[b]
            i-=1

            b-=1

another ways:

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.        """        if not nums1:            return         i=m+n-1        a=m-1        b=n-1        while  i>=0 and a>=0 and b>=0:            if nums1[a]>nums2[b]:                nums1[i]=nums1[a]                a-=1            else:                nums1[i]=nums2[b]                b-=1            i-=1        if b>=0:            nums1[:b+1]=nums2[:b+1]






0 0
原创粉丝点击