Merge Sorted Array
2016-05-19 15:46
393 查看
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.
思路:将两个有序数组合并成一个数组放在nums1中。考虑两种合并策略
(1)从前往后。这样的话需要另开一个数组用来保存临时的结果,最后将合并结果再复制到nums1中
(2)从后往前。由于nums1空间足够,这样的话不会影响nums1原来位置的数据。比较一下,选择从后往前比较
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
int i=m-1;
int j=n-1;
int index=m+n-1;
while(i!=-1&&j!=-1)
nums1[index--]=nums1[i]>nums2[j]?nums1[i--]:nums2[j--];
while(i!=-1)
nums1[index--]=nums1[i--];
while(j!=-1)
nums1[index--]=nums2[j--];
}
};
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.
思路:将两个有序数组合并成一个数组放在nums1中。考虑两种合并策略
(1)从前往后。这样的话需要另开一个数组用来保存临时的结果,最后将合并结果再复制到nums1中
(2)从后往前。由于nums1空间足够,这样的话不会影响nums1原来位置的数据。比较一下,选择从后往前比较
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
int i=m-1;
int j=n-1;
int index=m+n-1;
while(i!=-1&&j!=-1)
nums1[index--]=nums1[i]>nums2[j]?nums1[i--]:nums2[j--];
while(i!=-1)
nums1[index--]=nums1[i--];
while(j!=-1)
nums1[index--]=nums2[j--];
}
};
相关文章推荐
- Unity中的C#内存管理(二)
- iOS学习之——实例变量
- 鱼眼镜头畸变校正-OpenCV3.1.0和Matalb2012a
- 数据库事物隔离级别
- linux格式化磁盘命令
- DELIMITER关键词作用 替换结束符号
- 短租app简析
- jquery.base64.js简单使用
- [Elasticsearch] 聚合中的重要概念 - Buckets(桶)及Metrics(指标)
- Android之 MTP框架和流程分析 (1)
- 网络协议概述:物理层、连接层、网络层、传输层、应用层详解
- java高效导出excel
- Unity中的C#内存管理(一)
- 生成不重复的随机数的高效的算法
- iOS 如何布局
- PHP程序员常用的8款Laravel软件包
- ADO.NET实体数据模型
- HDU 2458 - Kindergarten
- 反爬虫四个基本策略
- 使用gulp插件来自动刷新页面。