88、Merge Sorted Array
2015-11-26 17:13
330 查看
题目:
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.
解题思路:
典型的归并排序。但由于存在如下输入:
Input: [1,0] 1
[2] 1
不可以用一般的从前向后的归并法,因为对于多于的元素无从安置,需要从后向前进行归并方可。
python 版本:
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.
解题思路:
典型的归并排序。但由于存在如下输入:
Input: [1,0] 1
[2] 1
不可以用一般的从前向后的归并法,因为对于多于的元素无从安置,需要从后向前进行归并方可。
python 版本:
class Solution(object): def merge(self, nums1, m, nums2, n): """ :type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: void Do not return anything, modify nums1 in-place instead. """ index = m+n-1 i,j = m-1,n-1 while(i>=0 and j>=0): if(nums1[i]>=nums2[j]): nums1[index] = nums1[i] index -= 1 i -= 1 else: nums1[index] = nums2[j] index -= 1 j -= 1 if(i==-1): while(j>=0): nums1[j] = nums2[j] j -= 1
相关文章推荐
- 【转】高精度的进制转换!!!!
- 为什么要学习Linux
- ubuntu——apt源镜像
- 设计模式初体验——工厂模式
- rem px em的区别是什么?
- AngularJS进阶(十一)AngularJS实现表格数据的编辑,更新和删除
- AngularJS进阶(十一)AngularJS实现表格数据的编辑,更新和删除
- linux下查看进程内存使用情况
- web进门第13天
- ***使用jQuery实现跨域提交表单数据
- (转)Android之shape与selector实现圆角
- Java——与 或 非 异或
- windows Service 之调试过程
- 百度地图(一)
- 从今天起,记录遇到的问题
- MVC Html.AntiForgeryToken() 防止CSRF攻击
- glibc中字符串处理的几个函数实现分析
- 天嵌E9卡片i.mx6q-Linux12.04搭建nfs环境以及从nfs启动开发板
- python2.7安装 利用pip安装其他镜像配置(解决 Trusted--Host 问题)
- JavaSE(07)(数组高级操作及日期格式)