zoukankan      html  css  js  c++  java
  • 微软面试

    题目描述:

      给定一个序列,是否可以通过栈输出递增序列。

    比如:

    5 4 3 2 1  ok   1 2 3 4 5

    1 4 2 3 5  ok   1 2 3 4 5

    5 2 4 3 1  Not ok

    思路:

    通过一个stack来模拟。while(如果遇到当前元素比栈顶元素大),就输出栈顶元素;否则就压入到栈中。

    通过lastval来标记上一个输出值。

    最后压入一个INF,清空队列。

    上来想到用栈模拟,没想通的地方是:

    1 应该用while循环比较栈顶元素和当前元素的大小,如果栈顶元素更小那么都应该弹出。

    2 但是5 4 3 2 1这种数据全都压在里面,不能清空。所以需要最后一个INF

    #include <iostream>
    #include <stack>
    #include <vector>
    #define INF 0x3f3f3f3f
    
    using namespace std;
    
    bool canGet(vector<int> a)
    {
        int n = a.size(), cnt = 0, lastVal = -INF;
        stack<int>sta;
        for(int i = 0; i < n; i ++){
            if(sta.size() == 0){
                sta.push(a[i]);
            }else{
                if(a[i] > sta.top()){
                    while(!sta.empty() && a[i] > sta.top()){
                        if(lastVal > sta.top()) return false;
                        lastVal = sta.top();
                        cout<<lastVal<<" a : "<<a[i]<<endl;
                        sta.pop();
                    }
                    sta.push(a[i]);
                }else{
                    sta.push(a[i]);
                }
            }
        }
        return true;
    }
    
    
    int tmp[5] = {1, 4, 2, 3, 5};
    
    int main()
    {
        vector<int>a;
        
        for(int i = 0; i < 5; i ++){
            a.push_back(tmp[i]);
        }a.push_back(INF);
        
        if(canGet(a)){
            cout<<"Can"<<endl;
        }else{
            cout<<"Can not"<<endl;
        }
        
        return 0;
    }

    冷静思考,准确实现!

  • 相关阅读:
    学习进度
    作业8:单元测试练习
    用户体验设计案例分析
    团队协作一
    需求分析
    结对编程——词频统计 2
    结对编程——词频统计
    个人项目-词频统计
    数组求和
    个人介绍和Github使用流程
  • 原文地址:https://www.cnblogs.com/luntai/p/6673416.html
Copyright © 2011-2022 走看看