题目:

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 and n respectively.

说明:无

实现:

精简实现:

 1 // 时间复杂度 O(m+n),空间复杂度 O(1)
 2 class Solution {
 3 public:
 4     void merge(int A[], int m, int B[], int n) {
 5         int i=m-1,j=n-1,k=m+n-1;
 6         while(i>=0&&j>=0)//从后面开始比较归并,直到有一个数组归并完
 7         {
 8           A[k--]=A[i]>B[j]?A[i--]:B[j--];//将大数赋给A[k]
 9         }
10         while(j>=0)//若B还没归并完,直接归并到A
11             A[k--]=B[j--];
12     }
13 };

 

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-03
  • 2022-01-01
  • 2022-12-23
  • 2022-12-23
  • 2022-01-20
猜你喜欢
  • 2022-12-23
  • 2021-07-05
  • 2022-12-23
  • 2021-08-23
  • 2021-06-29
  • 2022-12-23
  • 2021-11-03
相关资源
相似解决方案