lintcode:Merge Sorted Array
2015-10-14 20:55
295 查看
Given two sorted integer arrays A and B, merge B into A as one sorted array.
Example
A = [1, 2, 3, empty, empty], B = [4, 5]
After merge, A will be filled as [1, 2, 3, 4, 5]
Note
You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.
虽然AC,但很明显未充分利用有序的特点
Example
A = [1, 2, 3, empty, empty], B = [4, 5]
After merge, A will be filled as [1, 2, 3, 4, 5]
Note
You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.
1.提交1
class Solution { public: /** * @param A: sorted integer array A which has m elements, * but size of A is m+n * @param B: sorted integer array B which has n elements * @return: void */ void mergeSortedArray(int A[], int m, int B[], int n) { // write your code here int *res=new int[m+n]; for(int i=0;i<m;i++){ res[i]=A[i]; } for(int i=m;i<m+n;i++){ res[i]=B[i-m]; } sort(res,res+m+n);// memcpy(A,res,sizeof(int)*(m+n)); delete []res; } };
虽然AC,但很明显未充分利用有序的特点
2.提交2
class Solution { public: /** * @param A: sorted integer array A which has m elements, * but size of A is m+n * @param B: sorted integer array B which has n elements * @return: void */ void mergeSortedArray(int A[], int m, int B[], int n) { // write your code here //上个实现明显不好 //其实这个就是归并排序的归并阶段 int pa=m-1,pb=n-1,p=m+n-1; while(pa>=0&&pb>=0){ if(A[pa]>=B[pb]){ A[p]=A[pa]; p--; pa--; }else{ A[p]=B[pb]; p--; pb--; } } while(pa>=0){ A[p--]=A[pa--]; } while(pb>=0){ A[p--]=B[pb--]; } } };
相关文章推荐
- eclipse部署上Tomcat后的clean和publish功能
- RAC日志路径汇总
- 嵌入式编程时注意的事项
- AI顶级会议列表 & ACL相关
- PostgreSQL数据库监控中的统计学 - 对象空间的数据分布图
- 一道题采用两种设计模式:对比策略模式和模版方法
- 利用PHP SOAP实现WEB SERVICE
- MSSQL纵列转横列
- linux 查看端口是否被占用
- 数据仓库与数据集市的概念区别
- 细致的学习了一遍Android Material Design,简单做下笔记
- 【LeetCode从零单刷】Find Peak Element
- git环境的搭建
- 100 js js解析url地址获取参数
- 浅析Java中的final关键字
- 面试题——Servlet的生命周期
- matlab中size()函数的用法
- 论JAVA集合的实现细节,Map和List的联系
- 史上最详细的Android Studio系列教程四--Gradle基础
- PHP中soap的使用例子