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的元素考过去
解法二:现将数组A与数组B中的元素合并到一个ArrayList对象中,最后在拷贝到数组A中,运行时间可减小
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 |
相关文章推荐
- leetcode:Merge Sorted Array(合并两个有序数组到其中一个数组中)【面试算法题】
- Leetcode Merge Sorted Array
- Merge Sorted Array - LeetCode
- Leetcode_88_Merge Sorted Array
- LeetCode | Merge Sorted Array
- [LeetCode] Merge Sorted Array
- [LeetCode]Merge Sorted Array
- LeetCode刷题【Array】Merge Sorted Array
- LeetCode - 21/23/88 - Merge Sorted Lists/Array
- 【LeetCode】Merge Sorted Array
- Leetcode_c++: Merge Sorted Array (088)
- [LeetCode] Merge Sorted Array
- LeetCode 88:Merge Sorted Array
- Leetcode Merge Sorted Array
- 【leetcode】Merge Sorted Array
- leetcode 刷题之路 37 Merge Sorted Array
- [LeetCode] Merge Sorted Array
- leetcode:88 Merge Sorted Array-每日编程第三十一题
- [LeetCode]88 Merge Sorted Array
- LeetCode——Merge Sorted Array