[LeetCode 141,155][简单]环形链表/最小栈

落爺英雄遲暮 提交于 2020-02-06 00:26:04

141.环形链表
题目链接
显然的做法是用unordered_map,节约空间可以用快慢指针。

class Solution {
public:
    bool hasCycle(ListNode *head) {
        ios::sync_with_stdio(false);
        if(!(head && head -> next))return false;
        ListNode *p1 = head -> next;
        ListNode *p2 = p1 -> next;
        while(p1 && p2){
            if(p1 == p2)return true;
            p1 = p1 -> next;
            p2 = p2 -> next;
            if(p2)p2 = p2 -> next;
        }
        return false;
    }
};

155.最小栈
题目链接

class MinStack {
public:
    /** initialize your data structure here. */
    deque<int>mn;
    deque<int>ans;
    MinStack() {
        
    }
    
    void push(int x) {
        ans.emplace_back(x);
        if(mn.empty()||x <= mn.back())mn.emplace_back(x);
    }
    
    void pop() {
        if(ans.back()==mn.back())mn.pop_back();
        ans.pop_back();
    }
    
    int top() {
        return ans.back();
    }
    
    int getMin() {
        return mn.back();
    }
};
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!