您的位置:首页 > 其它

leetcode(十五)Merge Sorted Array

2014-07-24 19:19 239 查看
copyright:leetcode

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.

题目已假定,数组A的长度大于等于m+n

解法一:直接将数组B中元素直接插入到数组A中

index记录当前已合并(排好序)的位置,i表示数组B当前要插入的元素下表,当index==m+i时,数组A的所有元素已经合并完毕,剩下的仅仅是将数组B的元素考过去

public class Solution {
public void merge(int A[], int m, int B[], int n) {
int index = 0, tmp = 0;
for(int i=0;i < n;i++){
while(index < m+i && B[i] > A[index]){
index++;
//avoid case: B[i] > ANY of A
if(index == m+i)
break;
}
//when index == m+i means the merge of A has complished
for(int j=m+i;j > index;j--){
A[j] = A[j-1];
}
A[index++] = B[i];
}
}
}
Runtime: 408 ms

解法二:现将数组A与数组B中的元素合并到一个ArrayList对象中,最后在拷贝到数组A中,运行时间可减小

public class Solution {
public void merge(int A[], int m, int B[], int n) {
ArrayList<Integer> list = new ArrayList<Integer>();
int i=0,j=0;
for(;i < m && j < n;){
if(A[i] < B[j])
list.add(A[i++]);
else
list.add(B[j++]);
}
//		System.out.println("i:"+i+" j:"+j);//
if(i == m){
for(;j < n;)
list.add(B[j++]);
}else{
for(;i < m;)
list.add(A[i++]);
}

//copy elements to A
for(i=0;i < list.size();i++)
A[i] = list.get(i).intValue();
}
}

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