2014-05-10 23:45
原题:
Arrange the numbers in an array in alternating order. For example if the array is [a1, a2, a3, a4.. ]arrange the array such that b1<=b2>=b3<=b4 and so on. Sampe Input: 3 5 7 8 4 9 Sample Output: 3 < 5 > 4 < 8 >7 < 9
题目:给定一个数组,请调整元素顺序,使得数组满足a <= b >= c <= d ...这样的交替单调性。
解法:之前也有类似题目,不过那一题要求严格的大于和小于。如果是大于等于和小于等于的话,可以保证在O(n)时间内完成算法。只要按顺序调整相邻元素就可以达到题目要求了。
代码:
1 // http://www.careercup.com/question?id=5684901156225024 2 #include <algorithm> 3 #include <iostream> 4 #include <vector> 5 using namespace std; 6 7 class Solution { 8 public: 9 void arrangeArray(vector<int> &v) { 10 int n; 11 int i; 12 13 n = (int)v.size(); 14 if (n < 2) { 15 return; 16 } 17 18 int flag = 0; 19 for (i = 0; i < n - 1; ++i) { 20 if (flag ? v[i] < v[i + 1] : v[i] > v[i + 1]) { 21 myswap(v[i], v[i + 1]); 22 } 23 flag = !flag; 24 } 25 }; 26 private: 27 void myswap(int &x, int &y) 28 { 29 int tmp = x; 30 x = y; 31 y = tmp; 32 } 33 }; 34 35 int main() 36 { 37 int n; 38 int i; 39 vector<int> v; 40 Solution sol; 41 42 while (cin >> n && n > 0) { 43 v.resize(n); 44 for (i = 0; i < n; ++i) { 45 cin >> v[i]; 46 } 47 sol.arrangeArray(v); 48 49 for (i = 0; i < n; ++i) { 50 cout << v[i]; 51 cout << (i == n - 1 ? '\n' : ' '); 52 } 53 54 v.clear(); 55 } 56 57 return 0; 58 }