题目

这是一道面试题,题目如下:

合并 3 个递增数组A=[2,3,4,5,6,9,10], B=[6,9,10,11,13,15], C=[2,3,4,7,9,10],输出到D. 要求:

  1. D的每个元素也是递增(a1 <= a2) 不用去重)
  2. 不使用 api 和排序方法.
  3. 时间复杂度 O(n),空间复杂度为 O(1)。

代码

本示例使用 C# 实现,完整的代码,可以拿来即用

  1. namespace sortDemo
  2. {
  3. class Program
  4. {
  5. static void Main(string[] args)
  6. {
  7. int[] aArry = new int[] { 2, 3, 4, 5, 6, 9, 10 };
  8. int[] bArry = new int[] { 6, 9, 10, 11, 13, 15 };
  9. int[] cArry = new int[] { 2, 3, 4, 7, 9, 10 };
  10. // 申请一个数组e
  11. int[] eArry = Merge(bArry, cArry);
  12. int[] dArry = MergeT(aArry, eArry);
  13. for (int k = 0; k < dArry.Length; k++)
  14. {
  15. System.Console.WriteLine(dArry[k]);
  16. }
  17. }
  18. /// <summary>
  19. /// 融合两个数组,并排序
  20. /// </summary>
  21. /// <param name="a">数组a</param>
  22. /// <param name="b">数组b</param>
  23. /// <returns></returns>
  24. public static int[] Merge(int[] a, int[] b)
  25. {
  26. int[] answer = new int[a.Length + b.Length];
  27. int i = 0, j = 0, k = 0;
  28. while (i < a.Length && j < b.Length)
  29. answer[k++] = a[i] < b[j] ? a[i++] : b[j++];
  30. while (i < a.Length)
  31. answer[k++] = a[i++];
  32. while (j < b.Length)
  33. answer[k++] = b[j++];
  34. return answer;
  35. }
  36. /// <summary>
  37. /// 和上一个类似,代码比较紧凑
  38. /// </summary>
  39. /// <param name="a"></param>
  40. /// <param name="b"></param>
  41. /// <returns></returns>
  42. public static int[] MergeT(int[] a, int[] b)
  43. {
  44. int[] answer = new int[a.Length + b.Length];
  45. int i = a.Length - 1, j = b.Length - 1, k = answer.Length;
  46. while (k > 0)
  47. answer[--k] =
  48. (j < 0 || (i >= 0 && a[i] >= b[j])) ? a[i--] : b[j--];
  49. return answer;
  50. }
  51. }
  52. }

关于时间复杂度和空间复杂度参考:

语雀内容