Careercup - Facebook面试题 - 5435439490007040

2014-05-02 07:37

题目链接

原题:

// merge sorted arrays 'a' and 'b', each with 'length' elements, 

// in-place into 'b' to form a sorted result. assume that 'b' 

// has 2*length allocated space. 

// e.g. a = [1, 3, 5], b = [2, 4, 6] => b = [1, 2, 3, 4, 5, 6] 



//how to do it without rearanging the b array

题目:有两个排好序的数组a[]和b[],把a有序归并到b中去,保证b的空间充足。如何就地完成这个算法?

解法:从后往前归并就可以不用额外空间了。

代码:

 1 // http://www.careercup.com/question?id=5435439490007040

 2 #include <iostream>

 3 #include <vector>

 4 using namespace std;

 5 

 6 class Solution {

 7 public:

 8     void mergeTwoArray (vector<int> &a, vector<int> &b) {

 9         // merge a[] into b[].

10         int na = (int)a.size();

11         int nb = (int)b.size();

12 

13         b.resize(na + nb);

14 

15         int i, j, k;

16         

17         i = na - 1;

18         j = nb - 1;

19         k = na + nb - 1;

20         while (i >= 0 && j >= 0) {

21             b[k--] = a[i] > b[j] ? a[i--] : b[j--];

22         }

23         while (i >= 0) {

24             b[k--] = a[i--];

25         }

26     };

27 };

28 

29 int main()

30 {

31     vector<int> a, b;

32     int na, nb;

33     int i;

34     Solution sol;

35     

36     while (cin >> na >> nb && (na > 0 && nb > 0)) {

37         a.resize(na);

38         b.resize(nb);

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

40             cin >> a[i];

41         }

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

43             cin >> b[i];

44         }

45         sol.mergeTwoArray(a, b);

46         nb = (int)b.size();

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

48             i ? (cout << ' ', 1) : 1;

49             cout << b[i];

50         }

51         cout << endl;

52         

53         a.clear();

54         b.clear();

55     }

56     

57     return 0;

58 }

 

你可能感兴趣的:(Facebook)