美文网首页
Merge Sorted Array

Merge Sorted Array

作者: Leonlong | 来源:发表于2017-01-04 07:55 被阅读0次

    Given two sorted integer arrays A and B, merge B into A as one sorted array.
    ** Notice
    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.
    ExampleA = [1, 2, 3, empty, empty]
    , B = [4, 5]
    After merge, A will be filled as [1, 2, 3, 4, 5]

    合并两个排序好的数组,而且题目说明数组A的side大于m+n; 所以我们用的方法就是从两个数组最后一个数字比起,大的就放到m+n-1的位置去,然后调整index之后继续比下去直到一个数组先空为止,在判断把另一个有剩余的数组填进去。

    class Solution {
        /**
         * @param A: sorted integer array A which has m elements, 
         *           but size of A is m+n
         * @param B: sorted integer array B which has n elements
         * @return: void
         */
        public void mergeSortedArray(int[] A, int m, int[] B, int n) {
            // write your code here
            
            int i = m-1, j = n-1, k = m+n-1;
            while(i >= 0 && j >= 0){
                if(A[i] < B[j]){
                    A[k] = B[j];
                    k--;
                    j--;
                }else{
                    A[k] = A[i];
                    k--;
                    i--;
                }
            }
            
            while(i >= 0){
                A[k] = A[i];
                k--;
                i--;
            }
            
            while(j >= 0){
                A[k] = B[j];
                k--;
                j--;
            }
        }
    }
    
    

    相关文章

      网友评论

          本文标题:Merge Sorted Array

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