1. 程式人生 > 其它 >牛客 奇怪的排序問題(單調棧/遍歷)

牛客 奇怪的排序問題(單調棧/遍歷)

技術標籤:LintCode及其他OJ

文章目錄

1. 題目

連結:https://ac.nowcoder.com/acm/contest/10166/B
來源:牛客網

操場上有n個人排成一隊,這n個人身高互不相同,可將他們的身高視為一個1到n的排列。
這時需要把隊伍變成升序,也就是從矮到高排序。

每次可以選擇一個人,讓這個人和在他身後的人比高矮,如果比對方高,則交換位置並繼續下一次比較,直到比對方矮或者已經在隊尾。

現在給出數n和一個1到n的排列,求最少的選擇次數,使隊伍變為升序

示例1
輸入
4,[4,1,2,3]
返回值
1

備註:
n<=10^6
資料包含一個整數n和一個含有n個元素的陣列,表示從隊頭到隊尾的人的身高。
輸出一個整數表示答案。

2. 解題

  • 單調棧,當棧頂的身高 比 當前的大 ,需要移動一次
class Solution {
public:
    /**
     * 程式碼中的類名、方法名、引數名已經指定,請勿修改,直接返回方法規定的值即可
     * 
     * @param n int整型 
     * @param a int整型vector 
     * @return int整型
     */
    int wwork(int n, vector<int>& a) {
        // write code here
        int ans = 0;
        stack<
int> s; for(int i = 0; i < n; i++) { while(!s.empty() && s.top() > a[i]) { ans++; s.pop(); } s.push(a[i]); } return ans; } };
  • 直接反向遍歷,當前身高比後面最小的大,就需要移動一次
class Solution
{ public: /** * 程式碼中的類名、方法名、引數名已經指定,請勿修改,直接返回方法規定的值即可 * * @param n int整型 * @param a int整型vector * @return int整型 */ int wwork(int n, vector<int>& a) { // write code here int ans = 0, MIN = INT_MAX; for(int i = n-1; i >= 0; --i) { if(a[i] > MIN) ans++; MIN = min(MIN, a[i]); } return ans; } };

我的CSDN部落格地址 https://michael.blog.csdn.net/

長按或掃碼關注我的公眾號(Michael阿明),一起加油、一起學習進步!
Michael阿明