美文网首页
【Leetcode】88. Merge Sorted Array

【Leetcode】88. Merge Sorted Array

作者: 随时学丫 | 来源:发表于2018-06-30 20:01 被阅读13次

    88. Merge Sorted Array

    Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

    Note:

    • The number of elements initialized in nums1 and nums2 are m and n respectively.
    • You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.

    Example:

    Input:
    nums1 = [1,2,3,0,0,0], m = 3
    nums2 = [2,5,6],       n = 3
    
    Output: [1,2,2,3,5,6]
    

    维护三个 index,分别对应数组 A,数组 B,和结果数组。然后 A 和 B 同时从后往前扫,每次迭代中 A 和 B 指向的元素大的便加入结果数组中,然后 index-1,另一个不动。

    public void merge(int A[], int m, int B[], int n) {
            if(A==null || B==null)
                return;
            int idx1 = m-1;
            int idx2 = n-1;
            int len = m+n-1;
            while(idx1>=0 && idx2>=0)
            {
                if(A[idx1]>B[idx2])
                {
                    A[len--] = A[idx1--];
                }
                else
                {
                    A[len--] = B[idx2--];
                }
            }
            while(idx2>=0)
            {
                A[len--] = B[idx2--];
            }        
        }
    

    相关文章

      网友评论

          本文标题:【Leetcode】88. Merge Sorted Array

          本文链接:https://www.haomeiwen.com/subject/oikxuftx.html