亂序保序輸出
阿新 • • 發佈:2018-11-26
thinking:
(1)每次選擇輸出的數字是當前序列中最小的,記該數字下標為 index,數字為a
(2)檢查index 之後的最小數為b
(3)如果index之前有小於b且大於a的數字出現,說明這些數字是亂序的數字,要和a一行保序輸出
- 此處用 優先佇列會更有優勢!!!
int output_in_order(vector<int> &unordered_sequence) { int next_output = 1,got_output; priority_queue<int, vector<int>, greater<int> > pq; for(int 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; if(!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; }