LeetCode : 数组合并

题目描述


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 to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.


思路:这个关键可以想到从后往前走,比较方便,不需要开辟额外的空间

public class Solution {
    public void merge(int nums1[], int m, int nums2[], int n) {
        int i=m-1;
        int j=n-1;
        int index=m+n-1;
        while (i >= 0 && j >= 0)
            nums1[index--] = nums1[i] > nums2[j] ? nums1[i--] : nums2[j--]; 
        //因为最后要保存在nums1当中,所以如果B的全部插入到A中,A的顺序就不用管了
        while (j >= 0)
            nums1[index--] = nums2[j--];
        //这样的话,需要把B的再加到1里面
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_30363263/article/details/80270442