C#LeetCode刷题之#88-合并两个有序数组(Merge Sorted Array)
2024-10-09 11:35:45
问题
该文章的最新版本已迁移至个人博客【比特飞】,单击链接 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
分析:
显而易见,以上参考算法在最坏的情况下的时间复杂度为: 。
最新文章
- C#日志
- 学习微信小程序之css4设置颜色,单位表示,字体样式
- RichEdit 追加 RTF
- NSDate用法整理总结
- IGS_学习笔记07_IREP通过页面测试客户化Web Service调用(案例)
- Codeforces Educational Codeforces Round 3 D. Gadgets for dollars and pounds 二分,贪心
- webform在页面生成的代码与事件回传
- 本地安装MySQL详细教程
- ubuntu typora使用学习
- 2017-2018-2 20165312实验二《Java面向对象程序设计》实验报告
- CSS中你知道的display的值有多少?用了多少?
- Vue.js学习和第一个实例
- Python–logging模块知多少
- 你的灯亮着吗pdf –读书笔记
- ASP.NET Core Middleware (转载)
- mysql和redis之间互相备份
- 【BZOJ】1616: [Usaco2008 Mar]Cow Travelling游荡的奶牛(dp/-bfs)
- 【云安全与同态加密_调研分析(5)】云安全标准现状与统计——By Me
- Quartz_2_简单编程式任务调度使用(CronTrigger)
- SQL总结-----触发器
热门文章
- 从连接器组件看Tomcat的线程模型——BIO模式
- Ethical Hacking - GAINING ACCESS(20)
- 一张图就可以完美解决Java面试频次最高、GG最高的题目!快点收藏
- 【C#】NET截屏网页,生成网页快照开发——IECapt、CutyCapt
- 关系型数据库查询语言 SQL 和图数据库查询语言 nGQL 对比
- 任务调度中心xxl-job对外接口使用
- Crossword Answers -------行与列按序输出
- logrotate nginx日志切割
- seaborn分类数据可视化:散点图|箱型图|小提琴图|lv图|柱状图|折线图
- ken桑带你读源码 之scrapy