Leetcode 88.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.

 

归并排序

 1 class Solution {
 2 public:
 3     void merge(int A[], int m, int B[], int n) {
 4         vector<int> v(m+n,0);
 5         int i=0,j=0,k=0;
 6         while(i<m&&j<n){
 7             if(A[i]<B[j])
 8                 v[k++]=A[i++];
 9             else
10                 v[k++]=B[j++];
11             
12         }
13         while(i<m){
14             v[k++]=A[i++];
15             
16         }
17         while(j<n){
18             v[k++]=B[j++];
19         }
20         for(i=0;i<m+n;i++)
21             A[i]=v[i];
22     }
23 };

直接使用nums1的空间进行排序,从后向前依次merge

class Solution {
public:
    void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
        int i=m-1,j=n-1;
        int c=m+n-1;
        while(i>=0&&j>=0)
        {
            if(nums1[i]>=nums2[j])
                nums1[c--]=nums1[i--];
            else
                nums1[c--]=nums2[j--];
        }
        while(i>=0)
            nums1[c--]=nums1[i--];
        while(j>=0)
            nums1[c--]=nums2[j--];
    }
};

 

posted @ 2017-06-23 14:33  鸭子船长  阅读(200)  评论(0编辑  收藏  举报