Merge Sorted Array

这题开始的思路时错的,后来看了网上的总结

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 are m and n respectively.


分析: 这题的特点是最后的数据都保存在数组A 中。 刚开始我想从前往后复制,是错的。

             这和 merge two sorted list 不一样,如果最好数据都保存在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):
        allcur,acur,bcur = m+n-1,m-1,n-1
        for ind in range(m+n):
            if acur==-1:
                for indd in range(bcur+1):
                    A[indd] = B[indd]
                break;
            if bcur==-1:
                break;
                
            if A[acur]>=B[bcur]:
                A[allcur] = A[acur]
                acur -= 1
            else:
                A[allcur] = B[bcur]
                bcur -= 1
            allcur -= 1


C++

class Solution {
public:
    void merge(int A[], int m, int B[], int n) {
        
        int allcur=m+n-1, acur=m-1, bcur=n-1;
        for(int i=1;i<=m+n;i++){
            if(acur==-1){
                for(int j=0;j<(bcur+1);j++){
                    A[j]=B[j];
                }
                break;
            }
            if(bcur==-1){
                break;
            }
            
            A[allcur--] = A[acur]>=B[bcur] ? A[acur--]:B[bcur--];
        }
    }
};


总结:

作为C++ 新手, 这里有新的认识:

1.  对 cur += 1, cur -= 1.   可以使用 cur++ or cur--。  出现前面的语句,就可以看看是不是能转成后一个

2. C++ 里用了三目运算,一下子省了很多代码。 在非常简单的 if else 语句中,要学会用。 这个非常方便。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值