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; }
原文地址:http://blog.csdn.net/hustyangju/article/details/44837991