标签:
题目来源:http://www.lintcode.com/zh-cn/problem/merge-sorted-array/
C++版 VS2012测试通过
1 //#include <iostream>
2 //#include <vector>
3 //using namespace std;
4
5 class Solution {
6 public:
7 /**
8 * @param A: sorted integer array A which has m elements,
9 * but size of A is m+n
10 * @param B: sorted integer array B which has n elements
11 * @return: void
12 */
13 void mergeSortedArray(int A[], int m, int B[], int n) {
14 // write your code here
15 vector<int> v;
16 int i=0,j=0,k=0;
17 while(i<m && j<n)
18 {
19 if(A[i]<B[j])
20 v.push_back(A[i++]);
21 else
22 v.push_back(B[j++]);
23 }
24 while(i<m)
25 v.push_back(A[i++]);
26 while(j<n)
27 v.push_back(B[j++]);
28 vector<int>::iterator it;
29 for(it=v.begin();it<v.end();it++)
30 A[k++]=*it;
31 }
32 };
33
34 //测试
35 //int main()
36 //{
37 // Solution s;
38 //
39 // int a[5]={1,2,4};
40 // int b[2]={3,5};
41 // s.mergeSortedArray(a,3,b,2);
42 // for(int i=0;i<5;i++)
43 // cout<<a[i]<<" ";
44 //}
Python2.7版 spider测试通过
1 class Solution: 2 """ 3 @param A: sorted integer array A which has m elements, 4 but size of A is m+n 5 @param B: sorted integer array B which has n elements 6 @return: void 7 """ 8 def mergeSortedArray(self, A, m, B, n): 9 # write your code here 10 i, j, index = m - 1, n - 1, m + n - 1 11 while i >= 0 and j >= 0: 12 if A[i] > B[j]: 13 A[index] = A[i] 14 index, i = index - 1, i - 1 15 else: 16 A[index] = B[j] 17 index, j = index - 1, j - 1 18 while i >= 0: 19 A[index] = A[i] 20 index, i = index - 1, i - 1 21 while j >= 0: 22 A[index] = B[j] 23 index, j = index - 1, j - 1 24 25 #测试 26 #if __name__=="__main__": 27 # s=Solution() 28 # a=[1,2,4,0,0] 29 # b=[3,5] 30 # s.mergeSortedArray(a,3,b,2)
标签:
原文地址:http://www.cnblogs.com/hslzju/p/5612181.html