码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode || 88、Merge Sorted Array

时间:2015-04-14 21:40:11      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:leetcode   算法   归并排序   合并   

problem:

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 (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 mand n respectively.

Hide Tags
 Array Two Pointers
题意:原址合并两个已序数组

thinking:

(1)先合并再排序,O(m+n)lo(m+n)

(2)从后往前比较插入,不用移动元素,O(m+n)

code:

合并排序

class Solution {
public:
    void merge(int A[], int m, int B[], int n) {
        for(int i=0;i<n;i++)
            A[m+i]=B[i];
        sort(A,A+m+n);
    }
};
从后往前比较插入

class Solution {
public:
    void merge(int A[], int m, int B[], int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int index = m + n - 1;
        int aIndex = m - 1;
        int bIndex = n - 1;
        while(0 <= aIndex && 0 <= bIndex)
        {
            if (B[bIndex] > A[aIndex])
            {
                A[index--] = B[bIndex--];
            }
            else
            {
                A[index--] = A[aIndex--];
            }
        }
        
        while(0 <= aIndex)
        {
            A[index--] = A[aIndex--];
        }
        
        while(0 <= bIndex)
        {
            A[index--] = B[bIndex--];
        }
    }
};




leetcode || 88、Merge Sorted Array

标签:leetcode   算法   归并排序   合并   

原文地址:http://blog.csdn.net/hustyangju/article/details/45046781

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!