合并顺序数组

合并两个数组


给定含有n个元素的有序(非降序)整型数组a和含有m个元素的有序(非降序)整型数组b。合并两个数组中的元素到整型数组c,要求去除重复元素并保持c有序(非降序)。例子如下 a = 1, 2, 4, 8 b = 1, 3, 5, 8 c = 1, 2, 3, 4, 5, 8
Java代码 复制代码 收藏代码
  1. public class MergeArray {
  2. public static int[] doMerge(int[] a, int[] b) {
  3. int[] tmp = new int[a.length + b.length];
  4. tmp[0] = 0;
  5. int i = 0, j = 0, k = 0, count = 0;
  6. while (i <= a.length - 1 && j <= b.length - 1) {
  7. if (a[i] < b[j]) {
  8. if (a[i] != tmp[k]) {
  9. tmp[k++] = a[i++];
  10. count++;
  11. } else {
  12. i++;
  13. }
  14. } else if (a[i] > b[j]) {
  15. if (b[j] != tmp[k]) {
  16. tmp[k++] = b[j++];
  17. count++;
  18. } else {
  19. j++;
  20. }
  21. } else {
  22. if (a[i] != tmp[k]) {
  23. tmp[k++] = a[i++];
  24. count++;
  25. } else {
  26. i++;
  27. }
  28. j++;
  29. }
  30. }
  31. while (i <= a.length - 1) {
  32. if (a[i] != tmp[k]) {
  33. tmp[k++] = a[i++];
  34. count++;
  35. } else {
  36. i++;
  37. }
  38. }
  39. while (j <= b.length - 1) {
  40. if (b[j] != tmp[k]) {
  41. tmp[k++] = b[j++];
  42. count++;
  43. } else {
  44. j++;
  45. }
  46. }
  47. int[] c = new int[count];
  48. for (int m = 0; m <= count - 1 ; m++) {
  49. c[m] = tmp[m];
  50. }
  51. return c;
  52. }
  53. public static void main(String[] args) {
  54. int[] a = { 1, 2, 4, 8 };
  55. int[] b = { 1, 3, 5, 8 };
  56. int[] c = MergeArray.doMerge(a, b);
  57. for (int i = 0; i <= c.length - 1; i++) {
  58. System.out.print(c[i] + " ");
  59. }
  60. }
  61. }  
posted on 2013-02-12 16:24  蜜雪薇琪  阅读(306)  评论(0编辑  收藏  举报