Leetcode_merge-sorted-array(updated c++ and python version)
来源:互联网 发布:淘宝优惠券群怎么加入 编辑:程序博客网 时间:2024/05/19 06:50
地址:http://oj.leetcode.com/problems/merge-sorted-array/
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 andn respectively.
参考代码:
class Solution {public: void merge(int A[], int m, int B[], int n) { int pa = 0, pb = 0; for(; pa<m && pb<n; ) { if(A[pa]>B[pb]) { for(int i = m; i>pa; --i) { A[i]=A[i-1]; } A[pa] = B[pb]; ++m; ++pb; } ++pa; } while(pb<n) { A[m++] = B[pb++]; } }};
//SOLUTION TWO, which is better.class Solution {public:void merge(int A[], int m, int B[], int n) {if(!n)return;if(!m){for(int i = 0; i<n; ++i)A[i] = B[i];return;}int i = m-1, j = n-1;while(i>=0 && j>=0){if(A[i]>=B[j])A[i+j+1] = A[i--];elseA[i+j+1] = B[j--];}if(j<0)return;for(; j>=0; --j)A[j] = B[j];}};
Python:
class Solution:# @param A a list of integers# @param m an integer, length of A# @param B a list of integers# @param n an integer, length of B# @return nothingdef merge(self, A, m, B, n):if not B or not n:return;if not A:A = B[:]la = m-1lb = n-1while la>=0 and lb>=0:if A[la]>=B[lb]:A[la+lb+1] = A[la]la -= 1else:A[la+lb+1] = B[lb]lb -= 1if la<0:while lb>=0:A[lb]=B[lb]lb -= 1
0 0
- Leetcode_merge-sorted-array(updated c++ and python version)
- Leetcode_search-in-rotated-sorted-array-ii(updated c++ and python version)
- Leetcode_remove-duplicates-from-sorted-list (updated c++ and python version)
- Leetcode_Merge Sorted Array
- LeetCode_Merge Sorted Array
- leetcode_Merge Sorted Array
- leetcode_Merge Sorted Array
- Leetcode_Merge Sorted Array
- Leetcode_remove-duplicates-from-sorted-array-ii (c++ and python version)
- Leetcode_pascals-triangle (updated c++ and python version)
- Leetcode_unique-paths (updated c++ and python version)
- Leetcode_path-sum (updated c++ and python version)
- Leetcode_jump-game (updated c++ and python version)
- Leetcode_valid-number(updated c++ and python version)
- Leetcode_multiply-strings (updated c++ and python version)
- Leetcode_maximum-depth-of-binary-tree (updated c++ and python version)
- Leetcode_binary-tree-level-order-traversal (updated c++ and python version)
- Leetcode_pascals-triangle-ii (updated c++ and python version)
- redefinition of default parameter : parameter 1
- 约瑟夫环形算法 用c语言实现
- PHP随笔(文件操作)
- oracle查看锁表进程,杀掉锁表进程
- 交互设计、信息图、信息可视化、数据可视化技术资源汇总——设计师的领域,设计师说了算
- Leetcode_merge-sorted-array(updated c++ and python version)
- LeetCode之Remove Duplicates from Sorted List II
- wordpress ip更换(就是localhost问题)
- 人生的乖点
- android编译系统的makefile文件Android.mk写法如下
- 用ComboBox控件实现颜色下拉框
- Ubuntu 12.10中MyEclipse 10.6+下载+安装+破解
- /hadoop/src/contrib/build.xml
- 物理层技术综述