zoukankan      html  css  js  c++  java
  • 【LeetCode练习题】Merge Sorted Array

    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 (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 andn respectively.

    题目意思:

    将两个有序的数组合并成一个有序的数组。A和B合并到A中且A中的空间足够。

    解题思路:

    1,逗比的解法。

     1 int compare(const void *p1,const void *p2){
     2     int a = *(int *)p1;
     3     int b = *(int *)p2;
     4     return a-b;
     5 }
     6 class Solution {
     7 public:
     8     void merge(int A[], int m, int B[], int n) {
     9         for(int i = m,j = 0; i < m+n; i++,j++){
    10             A[i] = B[j];
    11         }
    12         qsort(A,m+n,sizeof(int),compare);
    13     }
    14 };

    2,题目想要我们这样解。

    跟合并两个链表是差不多的。区别在两个数组A和B从后往前来一一的作比较,而链表是从头开始比较的。

     1 class Solution {
     2 public:
     3     void merge(int A[], int m, int B[], int n) {
     4         int pa = m - 1, pb = n - 1, pr = m + n - 1;
     5         while(pa >= 0 && pb >= 0) {
     6             if(A[pa] > B[pb])
     7                 A[pr--] = A[pa--];
     8             else
     9                 A[pr--] = B[pb--];
    10         }
    11         while(pb >= 0)
    12             A[pr--] = B[pb--];
    13     }
    14 };

    ╭(╯^╰)╮……Anyway

    反正两种方法都AC了,所以,就这样吧。这题简单。

  • 相关阅读:
    数据结构之树和二叉树的一些基本概念
    面向对象的三大特点
    WOJ 1020
    C++ STL copy函数效率分析
    局部特化和类模板成员特化
    局部特化 & 特化
    back_inserter 与 iterator
    new期间的异常
    数组分配
    placement new和delete
  • 原文地址:https://www.cnblogs.com/4everlove/p/3651083.html
Copyright © 2011-2022 走看看