【LeetCode with Python】 Merge Sorted Array

来源:互联网 发布:three.min.js下载 编辑:程序博客网 时间:2024/05/29 17:34
博客域名:http://www.xnerv.wang
原题页面:https://oj.leetcode.com/problems/merge-sorted-array/
题目类型:数组,两指针问题
难度评价:★★
本文地址:http://blog.csdn.net/nerv3x3/article/details/3465682

Given two sorted integer arrays A and B, merge B into A as one sorted array.

Note:
You may assume that A has enough space (size that is greater or equal to m +n) to hold additional elements from B. The number of elements initialized in A and B arem andn respectively.


将一个有序数组B合并到另一个有序数组A。这题如果从数组头开始合并,则每一次都要整体移动数组A后面的元素,显然不是理想的方法。一种巧妙的做法是从两个数组尾部开始合并,这样就避免了大面积的数组元素移动。


class Solution:    # @param A  a list of integers    # @param m  an integer, length of A    # @param B  a list of integers    # @param n  an integer, length of B    # @return nothing    def merge(self, A, m, B, n):        if 0 == n:            return A        if 0 == m:            for i in range(0, n):                A[i] = B[i]            return A        index = m + n - 1        indexA = m - 1        indexB = n - 1        while indexA >= 0 and indexB >= 0:            if A[indexA] >= B[indexB]:                A[index] = A[indexA]                index -= 1                indexA -= 1            else:                A[index] = B[indexB]                index -= 1                indexB -= 1        if indexA >= 0:            pass        else:            for i in range(0, indexB + 1):                A[i] = B[i]

原创粉丝点击