[LeetCode] 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 to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.

考虑从后往前比较,这样就不会产生需要数据后移的问题了。时间复杂度O(n+m)

复制代码
 1 class Solution {
 2 public:
 3     void merge(int A[], int m, int B[], int n) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         int index = m + n - 1;
 7         int aIndex = m - 1;
 8         int bIndex = n - 1;
 9         while(0 <= aIndex && 0 <= bIndex)
10         {
11             if (B[bIndex] > A[aIndex])
12             {
13                 A[index--] = B[bIndex--];
14             }
15             else
16             {
17                 A[index--] = A[aIndex--];
18             }
19         }
20         
21         while(0 <= aIndex)
22         {
23             A[index--] = A[aIndex--];
24         }
25         
26         while(0 <= bIndex)
27         {
28             A[index--] = B[bIndex--];
29         }
30     }
31 };
复制代码
posted @   chkkch  阅读(5536)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示