问题:荷兰国旗问题,给定一个数组,让小于0的在左边,大于0的在右边,0在中间
如输入 [1, -2, 3, 0, -3, 0]
输出: [-2, -3, 0, 0, 3, 1]
思路:设置3个游标l = 0, r = n - 1, current = 0;l的左边小于0,r的右边大于0,中间为0
三种情况
a[current] < 0时, swap(a[current++], a[l++])
a[current] == 0时,current++
else swap(a[current], a[r--])
代码
#include <iostream>
#include <vector>
using namespace std;
vector<int> f(vector<int> a)
{
int l = 0, r = (int)a.size() - 1, current = l;
while (current <= r)
{
if (a[current] == 0)
{
current++;
}
else if (a[current] > 0)
{
swap(a[current], a[r--]);
}
else
{
swap(a[current++], a[l++]);
}
}
return a;
}
vector<int> g(vector<int> a, int size)
{
int n = rand() % size + 1;
for (int i = 0; i < n; i++)
{
if (rand() % 3 == 0)
{
a.push_back(rand() * -1);
}
else if (rand() % 3 == 1)
{
a.push_back(0);
}
else
{
a.push_back(rand());
}
}
return a;
}
bool check(vector<int> a)
{
vector<int> temp = a;
sort(a.begin(), a.end());
for (int i = 0; i < a.size() - 1; i++)
{
if ((a[i] < 0 && temp[i] < 0) || (a[i] == 0 && temp[i] == 0) || (temp[i] > 0 && a[i] > 0))
{
continue;
}
else
{
return false;
}
}
return true;
}
void test()
{
int N = 5000;
while (N--)
{
vector<int> a, res;
a = g(a, 5000);
res = f(a);
if (!check(res))
{
cout << "error" << endl;
return;
}
else
{
cout << N << endl;
}
}
cout << "OK" << endl;
}
int main()
{
test();
// vector<int> a;
// int n, x;
//
// cin >> n;
//
// for (int i = 0; i < n; i++)
// {
// cin >> x;
// a.push_back(x);
// }
//
// a = f(a);
//
// for (int i = 0; i < a.size(); i++)
// {
// cout << a[i] << ' ';
// }
// putchar(10);
return 0;
}