码迷,mamicode.com
首页 > 其他好文 > 详细

2016阿里实习笔试:乱序保序输出

时间:2015-04-03 11:32:01      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:阿里   乱序保序   

技术分享

thinking:

(1)每次选择输出的数字是当前序列中最小的,记该数字下标为 index,数字为a

(2)检查index 之后的最小数为b

(3)如果index之前有小于b且大于a的数字出现,说明这些数字是乱序的数字,要和a一行保序输出


code:

int output_in_order(vector<int> &unordered_sequence)
{
    int next_output = 1, got_output;

    priority_queue<int, vector<int>, greater<int> > pq;

    for (size_t i = 0; i < unordered_sequence.size(); i++)
    {
        pq.push(unordered_sequence[i]);

        if (pq.top() < next_output)
        {
            cout << "duplicated index or index <= 0 in the sequence" << endl;
            return -1;
        }

        got_output = 0;
        while (!pq.empty() && pq.top() == next_output)
        {
            if (got_output)
                cout << ", ";
            cout << next_output;
            next_output++;
            pq.pop();
            got_output = 1;
        }

        if (got_output)
            cout << endl;
    }

    if (pq.empty())
        return 0;

    cout << "missing some index in the sequence" << endl;

    return -2;
}


2016阿里实习笔试:乱序保序输出

标签:阿里   乱序保序   

原文地址:http://blog.csdn.net/hustyangju/article/details/44837991

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!