[LeetCode] Merge Sorted Array

来源:互联网 发布:sql in语句 编辑:程序博客网 时间:2024/06/15 07:37
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版



0 0
原创粉丝点击