【左神算法】基础班第二课(一)——荷兰国旗

问题:荷兰国旗问题,给定一个数组,让小于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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值