Merge Sorted Array——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 mand n respectively.
https://leetcode.com/problems/merge-sorted-array/
题意就是给定两个有序数组,把B中的元素合并到A中,可以假定A中有足够的空间。
怎么做才能是时间复杂度最低呢,与合并两个有序链表不同,两个数组的元素是可以通过下标直接访问的,而且要合并两个数组,元素肯定是要移动的,不像链表中改变一下next指针就可以了。最优的方式当时是从后往前遍历,因为合并的数组大小为m+n,那么合并后的数组最后一个元素的下标就是m+n-2,依次比较两个数组最末的元素,把较大的一个放置在合并后的数组的末端。
Talk is cheap>>
首先上清晰版,边界也清晰的处理了:
public void merge(int A[], int m, int B[], int n) { int i = 1, j = 1; if (m == 0) { System.arraycopy(B,0,A,0,n); return; } if (n == 0) return; while (i <= m && j <= n) { while (i <= m && j <= n && A[m - i] >= B[n - j]) { A[m + n - i - j + 1] = A[m - i]; i++; } while (i <= m && j <= n && A[m - i] < B[n - j]) { A[m + n - i - j + 1] = B[n - j]; j++; } } if (j <= n) { System.arraycopy(B, 0, A, 0, m + n - i - j + 2); } }
下面是压缩版,把边界条件缩入了while和if的判断中,并且压缩了while主循环,两个方法的执行时间几乎是一样的:
public void merge(int A[], int m, int B[], int n) { int i = 1, j = 1; while (i <= m && j <= n) { A[m + n - i - j + 1] = A[m - i] > B[n - j] ? A[m - i++] : B[n - j++]; } if (j <= n) { System.arraycopy(B, 0, A, 0, m + n - i - j + 2); } }