您的位置:首页 > 其它

[LeetCode] Merge Sorted Array

2014-05-01 00:32 323 查看
Problem
: 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 tom +n) to hold additional elements from B. The number of elements initialized in A and B arem andn respectively.

1.C++版

class Solution {
public:
void merge(int A[], int m, int B[], int n) {
int length=m+n;
int *result = new int[length];
int i=0,j=0,k=0;

while(i<m && j<n){
if(A[i]<=B[j]){
result[k++]=A[i++];
}else{
result[k++]=B[j++];
}
}

while(i<m){
result[k++]=A[i++];
}

while(j<n){
result[k++]=B[j++];
}

for(int i=0;i<length;++i){
A[i]=result[i];
}

delete []result;
}
};


2.Java版

public class Solution {
public void merge(int A[], int m, int B[], int n) {
int length=m+n;
int[] result=new int[length];
int i=0,j=0,k=0;

while(i<m && j<n){
if(A[i]<B[j]){
result[k++]=A[i++];
}else{
result[k++]=B[j++];
}
}

while(i<m){
result[k++]=A[i++];
}

while(j<n){
result[k++]=B[j++];
}

for(int index=0;index<length;++index){//Java不允许有相同名称的变量出现在同一个方法体中,这是其与C++的不同之处,请注意!!!
A[index]=result[index];
}
}
}


3.Python版

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: