《Cracking the Coding Interview》——第11章:排序和搜索——题目1

2014-03-21 20:35

题目:给定已升序排列的数组A和数组B,如果A有足够的额外空间容纳A和B,请讲B数组合入到A中。

解法:由后往前进行归并。

代码:

 1 // 11.1 Given two sorted array A and B, suppose A is large enough to hold them both. Merge B into A.

 2 #include <algorithm>

 3 #include <cstdio>

 4 using namespace std;

 5 

 6 void mergeBIntoA(int a[], int b[], int na, int nb)

 7 {

 8     if (na <= 0 || nb <= 0) {

 9         // invalid parameter

10         return;

11     }

12     

13     int *pmin, *pmax;

14     pmin = min(a, b);

15     pmax = max(a + na + nb, b + nb);

16     if (pmax - pmin < na + nb + nb) {

17         // the memories overlap

18         return;

19     }

20     

21     int i, j, k;

22     

23     i = na;

24     j = nb;

25     k = na + nb;

26     

27     while (i > 0 && j > 0) {

28         if (a[i - 1] > b[j - 1]) {

29             a[--k] = a[--i];

30         } else {

31             a[--k] = b[--j];

32         }

33     }

34     while (j > 0) {

35         a[--k] = b[--j];

36     }

37 }

38 

39 int main()

40 {

41     int *a, *b;

42     int na, nb;

43     int i;

44     

45     while (scanf("%d%d", &na, &nb) ==  2 && (na > 0 && nb > 0)) {

46         a = new int[na + nb];

47         b = new int[nb];

48         for (i = 0; i < na; ++i) {

49             scanf("%d", &a[i]);

50         }

51         for (i = 0; i < nb; ++i) {

52             scanf("%d", &b[i]);

53         }

54         mergeBIntoA(a, b, na, nb);

55         for (i = 0; i < na + nb; ++i) {

56             printf((i == 0 ? "%d" : " %d"), a[i]);

57         }

58         putchar('\n');

59         

60         delete[] a;

61         delete[] b;

62         a = nullptr;

63         b = nullptr;

64     }

65     

66     return 0;

67 }

 

你可能感兴趣的:(interview)