Leetcode: Merge Sorted Array
2015-06-05 21:11
288 查看
题目:
Given two sorted integer arrays A and B, merge B into A as one sorted array.
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.
思路分析:
我刚開始是从前面開始比較的,发现要移动非常多元素,后来从后面进行比較,代码异常简单!
C++參考代码:
Given two sorted integer arrays A and B, merge B into A as one sorted array.
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.
思路分析:
我刚開始是从前面開始比較的,发现要移动非常多元素,后来从后面进行比較,代码异常简单!
C++參考代码:
class Solution { public: void merge(int A[], int m, int B[], int n) { int k = m + n - 1; int i = m - 1; int j = n - 1; //两个数组同一时候从后面进行比較,将大的放在A数组末尾 while (i >= 0 && j >= 0) { A[k--] = A[i] > B[j] ? A[i--] : B[j--]; } //假设经过上面的while循环比較后B数组还有元素,则这些元素都小于A中最小元素,直接放入A数组最前面就好 while (j >= 0) { A[k--] = B[j--]; } } };
相关文章推荐
- 机器学习实战决策树之眼镜男买眼镜
- socket编程的select模型 转载
- 树莓派——显示设置
- java基础(十)--- 异常
- JavaScript学习笔记(三)
- 云服务器 性能测试之web压力测试
- 黑马程序员——OC语言基础——类与对象相关
- 小组自评、互评
- Android学习日记(2)
- 《软件调试艺术》读后感一
- ACM练习 最大最小值
- 迷宫问题
- Intellij Idea 14 修改字体
- 一次性移除一个 UIView 所有子视图的方法
- 【BZOJ】【3166】【HEOI2013】Alo
- mysql 架构
- 网络基础之TCP三次握手与四次挥手
- JDK动态代理和CGLIB动态代理+源码下载
- iOS 工作备注
- HDU 母牛的故事