问题

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3686 访问。

给定两个有序整数数组 nums1 和 nums2,将 nums2 合并到 nums1 使得 num1 成为一个有序数组。

说明:

  • 初始化 nums1 和 nums2 的元素数量分别为 m 和 n
  • 你可以假设 nums1 有足够的空间(空间大小大于或等于 m + n)来保存 nums2 中的元素。

输入:

nums1 = [1,2,3,0,0,0], m = 3

nums2 = [2,5,6],       n = 3

输出: [1,2,2,3,5,6]


Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

Note:

  • The number of elements initialized in nums1 and nums2 are m and n respectively.
  • You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.

Input:

nums1 = [1,2,3,0,0,0], m = 3

nums2 = [2,5,6],       n = 3

Output: [1,2,2,3,5,6]


示例

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3686 访问。

public class Program {

    public static void Main(string[] args) {
int[] nums1 = { 1, 3, 5, 7, 9, 0, 0, 0, 0, 0 };
int[] nums2 = { 2, 4, 6, 8, 10 }; Merge(nums1, 5, nums2, 5);
ShowArray(nums1); Console.ReadKey();
} private static void ShowArray(int[] array) {
foreach(var num in array) {
Console.Write($"{num} ");
}
Console.WriteLine();
} private static void Merge(int[] nums1, int m, int[] nums2, int n) {
//双指针法扫描数组
int point1 = m - 1;
int point2 = n - 1;
//指针,试图向第1个数组从后往前填充数值
int index = m + n - 1;
//从后往前扫描双数组
while(point1 >= 0 && point2 >= 0) {
//如果数组1中的值大,则将数组1中的数据放入数组1中的后面部分
if(nums1[point1] > nums2[point2]) {
nums1[index--] = nums1[point1--];
//否则,则将数组2中的数据放入数组1中的后面部分
} else {
nums1[index--] = nums2[point2--];
}
}
//当数组2中的值提前结束时,复制数组1中余下的部分
while(point1 >= 0) {
nums1[index--] = nums1[point1--];
}
//当数组1中的值提前结束时,复制数组2中余下的部分
while(point2 >= 0) {
nums1[index--] = nums2[point2--];
}
} }

以上给出1种算法实现,以下是这个案例的输出结果:

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3686 访问。

1 2 3 4 5 6 7 8 9 10

分析:

显而易见,以上参考算法在最坏的情况下的时间复杂度为:  。

最新文章

  1. C#日志
  2. 学习微信小程序之css4设置颜色,单位表示,字体样式
  3. RichEdit 追加 RTF
  4. NSDate用法整理总结
  5. IGS_学习笔记07_IREP通过页面测试客户化Web Service调用(案例)
  6. Codeforces Educational Codeforces Round 3 D. Gadgets for dollars and pounds 二分,贪心
  7. webform在页面生成的代码与事件回传
  8. 本地安装MySQL详细教程
  9. ubuntu typora使用学习
  10. 2017-2018-2 20165312实验二《Java面向对象程序设计》实验报告
  11. CSS中你知道的display的值有多少?用了多少?
  12. Vue.js学习和第一个实例
  13. Python–logging模块知多少
  14. 你的灯亮着吗pdf –读书笔记
  15. ASP.NET Core Middleware (转载)
  16. mysql和redis之间互相备份
  17. 【BZOJ】1616: [Usaco2008 Mar]Cow Travelling游荡的奶牛(dp/-bfs)
  18. 【云安全与同态加密_调研分析(5)】云安全标准现状与统计——By Me
  19. Quartz_2_简单编程式任务调度使用(CronTrigger)
  20. SQL总结-----触发器

热门文章

  1. 从连接器组件看Tomcat的线程模型——BIO模式
  2. Ethical Hacking - GAINING ACCESS(20)
  3. 一张图就可以完美解决Java面试频次最高、GG最高的题目!快点收藏
  4. 【C#】NET截屏网页,生成网页快照开发——IECapt、CutyCapt
  5. 关系型数据库查询语言 SQL 和图数据库查询语言 nGQL 对比
  6. 任务调度中心xxl-job对外接口使用
  7. Crossword Answers -------行与列按序输出
  8. logrotate nginx日志切割
  9. seaborn分类数据可视化:散点图|箱型图|小提琴图|lv图|柱状图|折线图
  10. ken桑带你读源码 之scrapy