Careercup - Microsoft面试题 - 5684901156225024

时间:2022-04-03 23:06:20

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:
Sample Output: < > < > <

题目:给定一个数组,请调整元素顺序,使得数组满足a <= b >= c <= d ...这样的交替单调性。

解法:之前也有类似题目,不过那一题要求严格的大于和小于。如果是大于等于和小于等于的话,可以保证在O(n)时间内完成算法。只要按顺序调整相邻元素就可以达到题目要求了。

代码:

 // http://www.careercup.com/question?id=5684901156225024
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std; class Solution {
public:
void arrangeArray(vector<int> &v) {
int n;
int i; n = (int)v.size();
if (n < ) {
return;
} int flag = ;
for (i = ; i < n - ; ++i) {
if (flag ? v[i] < v[i + ] : v[i] > v[i + ]) {
myswap(v[i], v[i + ]);
}
flag = !flag;
}
};
private:
void myswap(int &x, int &y)
{
int tmp = x;
x = y;
y = tmp;
}
}; int main()
{
int n;
int i;
vector<int> v;
Solution sol; while (cin >> n && n > ) {
v.resize(n);
for (i = ; i < n; ++i) {
cin >> v[i];
}
sol.arrangeArray(v); for (i = ; i < n; ++i) {
cout << v[i];
cout << (i == n - ? '\n' : ' ');
} v.clear();
} return ;
}