Merge Sorted Array II

Question

  1. Merge two given sorted integer array A and B into a new sorted integer array.
  2. Example
  3. A=[1,2,3,4]
  4. B=[2,4,5,6]
  5. return [1,2,2,3,4,4,5,6]
  6. Challenge
  7. How can you optimize your algorithm
  8. if one array is very large and the other is very small?

题解

上题要求 in-place, 此题要求返回新数组。由于可以生成新数组,故使用常规思路按顺序遍历即可。

Python

  1. class Solution:
  2. #@param A and B: sorted integer array A and B.
  3. #@return: A new sorted integer array
  4. def mergeSortedArray(self, A, B):
  5. if A is None or len(A) == 0:
  6. return B
  7. if B is None or len(B) == 0:
  8. return A
  9. C = []
  10. aLen, bLen = len(A), len(B)
  11. i, j = 0, 0
  12. while i < aLen and j < bLen:
  13. if A[i] < B[j]:
  14. C.append(A[i])
  15. i += 1
  16. else:
  17. C.append(B[j])
  18. j += 1
  19. # A has elements left
  20. while i < aLen:
  21. C.append(A[i])
  22. i += 1
  23. # B has elements left
  24. while j < bLen:
  25. C.append(B[j])
  26. j += 1
  27. return C

C++

  1. class Solution {
  2. public:
  3. /**
  4. * @param A and B: sorted integer array A and B.
  5. * @return: A new sorted integer array
  6. */
  7. vector<int> mergeSortedArray(vector<int> &A, vector<int> &B) {
  8. if (A.empty()) return B;
  9. if (B.empty()) return A;
  10. int aLen = A.size(), bLen = B.size();
  11. vector<int> C;
  12. int i = 0, j = 0;
  13. while (i < aLen && j < bLen) {
  14. if (A[i] < B[j]) {
  15. C.push_back(A[i]);
  16. ++i;
  17. } else {
  18. C.push_back(B[j]);
  19. ++j;
  20. }
  21. }
  22. // A has elements left
  23. while (i < aLen) {
  24. C.push_back(A[i]);
  25. ++i;
  26. }
  27. // B has elements left
  28. while (j < bLen) {
  29. C.push_back(B[j]);
  30. ++j;
  31. }
  32. return C;
  33. }
  34. };

Java

  1. class Solution {
  2. /**
  3. * @param A and B: sorted integer array A and B.
  4. * @return: A new sorted integer array
  5. */
  6. public ArrayList<Integer> mergeSortedArray(ArrayList<Integer> A, ArrayList<Integer> B) {
  7. if (A == null || A.isEmpty()) return B;
  8. if (B == null || B.isEmpty()) return A;
  9. ArrayList<Integer> C = new ArrayList<Integer>();
  10. int aLen = A.size(), bLen = B.size();
  11. int i = 0, j = 0;
  12. while (i < aLen && j < bLen) {
  13. if (A.get(i) < B.get(j)) {
  14. C.add(A.get(i));
  15. i++;
  16. } else {
  17. C.add(B.get(j));
  18. j++;
  19. }
  20. }
  21. // A has elements left
  22. while (i < aLen) {
  23. C.add(A.get(i));
  24. i++;
  25. }
  26. // B has elements left
  27. while (j < bLen) {
  28. C.add(B.get(j));
  29. j++;
  30. }
  31. return C;
  32. }
  33. }

源码分析

分三步走,后面分别单独处理剩余的元素。

复杂度分析

遍历 A, B 数组各一次,时间复杂度 O(n), 空间复杂度 O(1).

Challenge

两个倒排列表,一个特别大,一个特别小,如何 Merge?此时应该考虑用一个二分法插入小的,即内存拷贝。