zoukankan      html  css  js  c++  java
  • LeetCode

    Merge Sorted Array

    2013.12.27 01:18

    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.

    Solution1:

      First solution is simple and foolish enough, just put them together and sort it.

      Time complexity is O((m + n) * log(m + n)), space complexity is O(1).

    Accepted code:

     1 #include <algorithm>
     2 using namespace std;
     3 
     4 class Solution {
     5 public:
     6     void merge(int A[], int m, int B[], int n) {
     7         // IMPORTANT: Please reset any member data you declared, as
     8         // the same Solution instance will be reused for each test case.
     9         for(int i = m; i < m + n; ++i){
    10             A[i] = B[i - m];
    11         }
    12         sort(A, A + m + n);
    13     }
    14 };

    Solution2:

      Merge two arrays with O(m + n) extra space. Time complexity is O(m + n), space complexity is O(m + n). In-place merge seems more efficient, but somewhat a little tricky to understand. I'll put my in-place merge solution here when I grab the idea.

      Time complexity is O(m + n), space complexity is O(m + n).

    Accepted code:

     1 #include <cstdlib>
     2 using namespace std;
     3 
     4 class Solution {
     5 public:
     6     void merge(int A[], int m, int B[], int n) {
     7         // IMPORTANT: Please reset any member data you declared, as
     8         // the same Solution instance will be reused for each test case.
     9         int *C = nullptr;
    10         
    11         if(nullptr == A || nullptr == B || m < 0 || n <= 0){
    12             return;
    13         }
    14         
    15         C = new(nothrow) int[m + n];
    16         if(nullptr == C){
    17             printf("Error: bad memory allocation.");
    18             exit(0);
    19         }
    20         int i, j, k;
    21         
    22         i = j = k = 0;
    23         while(i < m && j < n){
    24             if(A[i] < B[j]){
    25                 C[k++] = A[i++];
    26             }else{
    27                 C[k++] = B[j++];
    28             }
    29         }
    30         while(i < m){
    31             C[k++] = A[i++];
    32         }
    33         while(j < n){
    34             C[k++] = B[j++];
    35         }
    36         memcpy(A, C, (m + n) * sizeof(A[0]));
    37         delete[] C;
    38     }
    39 };
  • 相关阅读:
    docker PXC MYSQL集群节点启动失败/节点顺序消失/只剩一个节点存在问题的解决
    springgateway
    rabbitMQ重复消费(结合死循环重发那一篇看)
    rabbitMq可靠性投递之手动ACK
    3表查询,1:多:多,根据1查多再查多
    tp后台注册登录配置项
    volist/foreach下,点击循环中的一个进行操作
    生成随机订单号
    省市县的下拉列表
    银行下拉列表
  • 原文地址:https://www.cnblogs.com/zhuli19901106/p/3493412.html
Copyright © 2011-2022 走看看