(数组)leetcode 88:Merge Sorted Array
2016-01-07 22:54
519 查看
水平有限,不足之处还望指正。
题目:
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 nums1and nums2 are m and n respectively.
题意:
给出两个有序的数组nums1和nums2,合并nums2到nums1中并保持原有顺,已确保nums1有足够的空间。
解题思路:
这里给出升序合并。在nums1(从m+n-1递减)的尾部从后向前逐个插入nums1(从m-1递减)与nums2(从n-1递减)中较大的数。时间复杂度为O(m+n)
AC代码如下(含有main函数,VS2013中可直接运行):
题目:
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 nums1and nums2 are m and n respectively.
题意:
给出两个有序的数组nums1和nums2,合并nums2到nums1中并保持原有顺,已确保nums1有足够的空间。
解题思路:
这里给出升序合并。在nums1(从m+n-1递减)的尾部从后向前逐个插入nums1(从m-1递减)与nums2(从n-1递减)中较大的数。时间复杂度为O(m+n)
AC代码如下(含有main函数,VS2013中可直接运行):
#include <iostream> #include <vector> using namespace std; class Solution { public: //升序合并 //首先确保nums1的大小至少等于m+n void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) { int index = m + n - 1; int s1Index = m - 1; int s2Index = n - 1; //从后向前逐个插入nums1与nums2中较大的数 while (s1Index>=0 && s2Index>=0) { nums1[index--] = nums2[s2Index] >= nums1[s1Index] ? nums2[s2Index--] : nums1[s1Index--]; } while (s1Index>=0) { nums1[index--] = nums1[s1Index--]; } while (s2Index >= 0) { nums1[index--] = nums2[s2Index--]; } } }; int main() { vector<int> nums1 = { 1, 5, 7, 9 }; vector<int> nums2 = { 2, 4, 6, 8, 10 }; Solution my_solution; int n = nums2.size(); while (n > 0) { nums1.push_back(0); n--; } my_solution.merge(nums1, nums1.size()-nums2.size(), nums2, nums2.size()); for (int i = 0; i < nums1.size(); i++) cout << nums1[i] << " "; cout << endl; return 0; }
相关文章推荐
- JAVA源码学习-ArrayList
- 一起talk C栗子吧(第九十 二回:C语言实例--浅谈typedef)
- AppBarLayout、ViewPager、Fragment实现页面左右滑动
- 学习资源
- 华为oj 字符串最后一个单词的长度
- UML类图关系(泛化、继承、实现、依赖、关联、聚合、组合)
- 入门训练 Fibonacci数列
- MySQL安装及问题
- 递归经典案例汉诺塔 python实现
- Mac安装Office软件
- 【读书笔记】代码整洁之道(6)
- [读书笔记]C#学习笔记一: .Net Framwork
- Java集合---ArrayList的实现原理
- Java与C语法上的区别
- php.ini文件中的include_path设置
- [经验技巧] 路由mini安装OpenWRT源的Transmission插件,实现PT下载(需SSH)
- 4.10 VideoView,SurfaceView,MediaPlayer,
- 重写逻辑表达式
- css014 响应式web设计
- android基础回顾笔记1--四大组件