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.

最新文章

  1. 用SignalR 2.0开发客服系统[系列2:实现聊天室]
  2. Java基础回顾
  3. jax-ws开发总结
  4. c语言中的文件流
  5. 修改更新源sources.list,提高软件下载安装速度(提供Kali 2.0 更新源)
  6. CSS clearfix
  7. BestCoder Round #69 (div.2)(hdu5611)
  8. POJ-1573 Robot Motion模拟
  9. 九、JSP入门(1)
  10. 《ASP.NET Core In Action》读书笔记系列四 创建ASP.NET Core 应用步骤及相应CLI命令
  11. spring一些简单小注意知识点
  12. 备份还原数据数据库(固定IP版)
  13. Java try和catch的使用介绍
  14. Vue内置的Component标签用于动态切换组件
  15. 6.Django扩展
  16. 【Revit API】脱离中心文件
  17. Linux DMA Engine framework(2)_功能介绍及解接口分析
  18. zend 2.2 db select 使用例子
  19. Linux 基础教程 25-命令和文件查找
  20. P2075 [NOIP2012T5]借教室 区间更新+二分查找

热门文章

  1. 【前缀和】【分类讨论】hdu5163 Taking Bus
  2. Problem M: 第几天——C语言初学者百题大战之十八
  3. jvm-监视管理控制台-jconsole
  4. [Javascript]js判断是否为undefined类型
  5. 【SQL】查询数据库中某个字段有重复值出现的信息
  6. 微信开发之消息接收与回复--weixin-java-tools
  7. Discuz! 7.1 &amp; 7.2 远程代码执行漏洞
  8. Less 简介
  9. GDB基本命令(整合)(转)
  10. Java 创建用户异常类、将异常一直向上抛、 throw和throws的区别