当前位置: 首页 > 文档资料 > LeetCode 题解 >

Array - Merge Sorted Array

优质
小牛编辑
125浏览
2023-12-01

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.

A和B都已经是排好序的数组,我们只需要从后往前比较就可以了。

因为A有足够的空间容纳A + B,我们使用游标i指向m + n - 1,也就是最大数值存放的地方,从后往前遍历A,B,谁大就放到i这里,同时递减i。

代码如下:

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