leetcode: Merge Sorted Array O(n)解法
2014-08-04 22:03
260 查看
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 andn respectively.
如果按照从前往后进行比较排序的方法,则根据数组的性质必须在插入一个元素后,其往后的所有元素需要向后进行移动一位。这样下来,将发生多次一位操作,时间效率会大幅度降低。现在换一种思路,我们从后往前进行插入排序,即先确定第m+n-1个位置上的元素值,再确定m+n-2个位置上的元素值,然后依次确定前面个每个元素,这样每个元素最多移动依次就可以获得最后的排序队列。下面为从后往前排序的源代码:
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 andn respectively.
如果按照从前往后进行比较排序的方法,则根据数组的性质必须在插入一个元素后,其往后的所有元素需要向后进行移动一位。这样下来,将发生多次一位操作,时间效率会大幅度降低。现在换一种思路,我们从后往前进行插入排序,即先确定第m+n-1个位置上的元素值,再确定m+n-2个位置上的元素值,然后依次确定前面个每个元素,这样每个元素最多移动依次就可以获得最后的排序队列。下面为从后往前排序的源代码:
class Solution { public: void merge(int A[], int m, int B[], int n) { int na=m-1; int nb=n-1; for(int i=m+n-1;i>=0;i--) { if(na<0) { A[i]=B[nb--]; } else if(nb<0) { return ; } else { if(A[na]>=B[nb]) { A[i]=A[na--]; } else { A[i]=B[nb--]; } } } } };
相关文章推荐
- [LeetCode] Merge Sorted Array
- LeetCode removeDuplicatesFromSortedArray两种解法方法
- LeetCode(088) Merge Sorted Array(Java)
- LeetCode(88) Merge Sorted Array
- LeetCode-Merge Sorted Array
- Leetcode Problem.88 —Merge Sorted Array
- 【LeetCode】Merge Sorted Array
- [leetCode]Merge Sorted Array
- LeetCode——Merge Sorted Array
- [LeetCode] Merge Sorted Array [22]
- LeetCode|Merge Two Sorted Lists/Merge Sorted Array
- LeetCode编程练习 - Merge Sorted Array学习心得
- [LeetCode] Merge Sorted Array 混合插入有序数组
- LeetCode | Merge Sorted Array(归并有序数组)
- LeetCode 088 Merge Sorted Array
- leetcode 29: Merge Sorted Array
- Leetcode Merge Sorted Array
- leetcode:Remove Duplicates from Sorted Array II 菜鸟解法
- leetcode_Merge Sorted Array
- LeetCode || Merge Sorted Array