88. Merge Sorted Array【easy】
2024-08-26 11:40:21
88. Merge Sorted Array【easy】
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively.
解法一:
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
int i = m - ;
int j = n - ;
int len = m + n - ; if (n == )
{
return;
} while (i >= && j >=)
{
if (nums1[i] >= nums2[j])
{
nums1[len--] = nums1[i--];
}
else
{
nums1[len--] = nums2[j--];
}
} /*
while (i >= 0)
{
nums1[len--] = nums1[i--];
}
*/ while (j >= )
{
nums1[len--] = nums2[j--];
}
}
};
从后向前搞,nums2完毕之后就不用处理nums1了,因为都是往nums1中合并的
解法二:
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
int i = m - , j = n - , tar = m + n - ;
while (j >= ) {
nums1[tar--] = i >= && nums1[i] > nums2[j] ? nums1[i--] : nums2[j--];
}
}
};
This code relies on the simple observation that once all of the numbers from nums2
have been merged into nums1
, the rest of the numbers in nums1
that were not moved are already in the correct place.
最新文章
- 用SignalR 2.0开发客服系统[系列2:实现聊天室]
- Java基础回顾
- jax-ws开发总结
- c语言中的文件流
- 修改更新源sources.list,提高软件下载安装速度(提供Kali 2.0 更新源)
- CSS clearfix
- BestCoder Round #69 (div.2)(hdu5611)
- POJ-1573 Robot Motion模拟
- 九、JSP入门(1)
- 《ASP.NET Core In Action》读书笔记系列四 创建ASP.NET Core 应用步骤及相应CLI命令
- spring一些简单小注意知识点
- 备份还原数据数据库(固定IP版)
- Java try和catch的使用介绍
- Vue内置的Component标签用于动态切换组件
- 6.Django扩展
- 【Revit API】脱离中心文件
- Linux DMA Engine framework(2)_功能介绍及解接口分析
- zend 2.2 db select 使用例子
- Linux 基础教程 25-命令和文件查找
- P2075 [NOIP2012T5]借教室 区间更新+二分查找
热门文章
- 【前缀和】【分类讨论】hdu5163 Taking Bus
- Problem M: 第几天——C语言初学者百题大战之十八
- jvm-监视管理控制台-jconsole
- [Javascript]js判断是否为undefined类型
- 【SQL】查询数据库中某个字段有重复值出现的信息
- 微信开发之消息接收与回复--weixin-java-tools
- Discuz! 7.1 &; 7.2 远程代码执行漏洞
- Less 简介
- GDB基本命令(整合)(转)
- Java 创建用户异常类、将异常一直向上抛、 throw和throws的区别