《leetCode》:Merge Sorted Array
2015-12-24 21:04
447 查看
题目
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的尾端即可。
//思路:从后往前遍历 void merge(int* nums1, int m, int* nums2, int n) { if(n<1){ return ; } if(m<1){//第一个数组元素为空 for(int i=0;i<n;i++){ nums1[i]=nums2[i]; } return ; } int index=m+n-1; int p1=m-1; int p2=n-1; while(p1>=0&&p2>=0){ if(nums1[p1]>=nums2[p2]){ nums1[index--]=nums1[p1]; p1--; } else if(nums1[p1]<nums2[p2]){ nums1[index--]=nums2[p2]; p2--; } } //如果是p2<0退出,则就已完成,如果是p1<0退出,则还需要将p2个元素拷贝要nums1中 if(p1<0&&p2>=0){ for(int i=0;i<=p2;i++){ nums1[i]=nums2[i]; } } }
相关文章推荐
- Go 基本命令
- Android 常用的性能分析工具详解:GPU呈现模式, TraceView, Systrace, HirearchyViewer
- 决策树C++实现
- string赋值地址问题
- 【shell脚本】批量创建和删除用户
- 如何写一个简单的android服务
- 数据结构
- 小记:xml画一个爱心。
- MySQL存储过程
- c#之线性表
- IOS里的TaggedPointer[NSString篇]
- Phoenix的数据类型和操作符、函数
- android中图片的三级cache策略(内存、文件、网络)之三:文件缓存策略
- 第十六周--数据结构--项目一-- 插入排序之显示显示插入过程
- osgOcean+VS2010+Win7编译方法
- 招聘网站需求分析
- 笔试题-反转字符串和按单词反转字符串
- android中图片的三级cache策略(内存、文件、网络) 一
- 单击右键弹出快捷菜单,并删除list control中的选中项
- Objective-C 集合之NSDictionary的常用方法