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

 

新建一个数组,将原来两个数组从小到大加入这个数组中,最后再复制到A数组里。其实可以有更省空间和时间的方法。从将A和B中的数从大到小添加到A数组的末尾,不会在使用前损坏A里的前m个数,同时也不用多开一个数组。

 

 

class Solution {
public:
    void merge(int A[], int m, int B[], int n) {
        int C[m+n];
        int i;
        int point_A = 0, point_B = 0;
        for(i = 0;i < m + n ;i ++)
        {
            if(point_A == m)
            {
                C[i] = B[point_B++];
            }
            else if(point_B == n)
            {
                C[i] = A[point_A++];
            }
            else if(A[point_A] > B[point_B])
            {
                C[i] = B[point_B++];
            }
            else
            {
                C[i] = A[point_A++];
            }
        }
        for(i = 0;i < m + n ;i ++)
        {
            A[i] = C[i];
        }
    }
};

 

 

你可能感兴趣的:(随记,面试切题)