zoukankan      html  css  js  c++  java
  • lc 0226

    ✅ 232. 用栈实现队列

    https://leetcode-cn.com/problems/implement-queue-using-stacks

    描述

    使用栈实现队列的下列操作:
    
    push(x) -- 将一个元素放入队列的尾部。
    pop() -- 从队列首部移除元素。
    peek() -- 返回队列首部的元素。
    empty() -- 返回队列是否为空。
    示例:
    
    MyQueue queue = new MyQueue();
    
    queue.push(1);
    queue.push(2);  
    queue.peek();  // 返回 1
    queue.pop();   // 返回 1
    queue.empty(); // 返回 false
    说明:
    
    你只能使用标准的栈操作 -- 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。
    你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
    假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)。
    
    
    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/implement-queue-using-stacks
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
    

    解答

    class MyQueue {
    private:
        stack<int> s1; // 输入栈
        stack<int> s2;  // 输出栈
    public:
        /** Initialize your data structure here. */
        MyQueue() {
        }
        
        /** Push element x to the back of queue. */
        void push(int x) {
            s1.push(x);
        }
        
        /** Removes the element from in front of queue and returns that element. */
        int pop() {
            if(s2.empty()) 
            {
                while(!s1.empty()) 
                {
                    int tmp = s1.top();
                    s1.pop();
                    s2.push(tmp);
                }
            }
            int ret = s2.top();
            s2.pop();
            return ret;
        }
        
        /** Get the front element. */
        int peek() {
            int ret = this->pop();
            s2.push(ret);
            return ret;
        }// tt 上述这个 peek 是非常nice 的,他reuse 了pop。
        
        /** Returns whether the queue is empty. */
        bool empty() {
            return s1.empty()&& s2.empty();
        }
    };
    

    c

    //C语言:线性表处理 
    //tt 但是这个没有使用stack 操作,仅仅是数组操作。
    
    typedef struct {
        int front;
        int rear;
        int val[1000];
    } MyQueue;
    /*
    tt queue looks like:
    
    [-----front********rear------]
    */
    /** Initialize your data structure here. */
    
    MyQueue* myQueueCreate() {
        MyQueue *ret = (MyQueue*) malloc (sizeof(MyQueue));
        ret->front = 0;
        ret->rear = 0;
        memset(ret->val, 0, sizeof(int) * 1000);
        return ret;
    }
    
    /** Push element x to the back of queue. */
    void myQueuePush(MyQueue* obj, int x) {
        obj->val[obj->rear++] = x;
    }
    
    /** Removes the element from in front of queue and returns that element. */
    int myQueuePop(MyQueue* obj) {
        int ret = obj->val[obj->front];
        obj->val[obj->front] = 0;
        (obj->front)++;
        return ret;
    }
    
    /** Get the front element. */
    int myQueuePeek(MyQueue* obj) {
        return obj->val[obj->front];
    }
    
    /** Returns whether the queue is empty. */
    bool myQueueEmpty(MyQueue* obj) {
        return obj->front == obj->rear;
    }
    
    void myQueueFree(MyQueue* obj) {
        memset(obj, 0, sizeof(MyQueue));
    }
    
    /**
    执行用时 :
    4 ms
    , 在所有 C 提交中击败了
    59.42%
    的用户
    内存消耗 :
    7.2 MB
    , 在所有 C 提交中击败了
    44.34%
    的用户
    */
    

    py

    python 双栈
    
    class MyQueue(object):
    
        def __init__(self):
            """
            Initialize your data structure here.
            """
            self.instack = []
            self.outstack = []
    
        def push(self, x):
            """
            Push element x to the back of queue.
            :type x: int
            :rtype: None
            """
            self.instack.append(x)
    
        def pop(self):
            """
            Removes the element from in front of queue and returns that element.
            :rtype: int
            """
            if len(self.outstack) == 0:
                while self.instack:
                    self.outstack.append(self.instack.pop())
            return self.outstack.pop()
    
        def peek(self):
            """
            Get the front element.
            :rtype: int
            """
            if len(self.outstack) == 0:
                while self.instack:
                    self.outstack.append(self.instack.pop())
            return self.outstack[-1]
        def empty(self):
            """
            Returns whether the queue is empty.
            :rtype: bool
            """
            return len(self.instack) == 0 and len(self.outstack) == 0
    
    
    # Your MyQueue object will be instantiated and called as such:
    # obj = MyQueue()
    # obj.push(x)
    # param_2 = obj.pop()
    # param_3 = obj.peek()
    # param_4 = obj.empty() 
    

    ✅ 496. 下一个更大元素 I

    https://leetcode-cn.com/problems/next-greater-element-i

    描述

    给定两个没有重复元素的数组 nums1 和 nums2 ,其中nums1 是 nums2 的子集。找到 nums1 中每个元素在 nums2 中的下一个比其大的值。
    
    nums1 中数字 x 的下一个更大元素是指 x 在 nums2 中对应位置的右边的第一个比 x 大的元素。如果不存在,对应位置输出-1。
    
    示例 1:
    
    输入: nums1 = [4,1,2], nums2 = [1,3,4,2].
    输出: [-1,3,-1]
    解释:
        对于num1中的数字4,你无法在第二个数组中找到下一个更大的数字,因此输出 -1。
        对于num1中的数字1,第二个数组中数字1右边的下一个较大数字是 3。
        对于num1中的数字2,第二个数组中没有下一个更大的数字,因此输出 -1。
    示例 2:
    
    输入: nums1 = [2,4], nums2 = [1,2,3,4].
    输出: [3,-1]
    解释:
        对于num1中的数字2,第二个数组中的下一个较大数字是3。
        对于num1中的数字4,第二个数组中没有下一个更大的数字,因此输出 -1。
    注意:
    
    nums1和nums2中所有元素是唯一的。
    nums1和nums2 的数组大小都不超过1000。
    
    
    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/next-greater-element-i
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
    

    解答

    思路:

    s1: 定位 nums1 中各个元素在 nums 2 中的位置 pos
    s2: 从这个pos 往后遍历找max,(这里可以优化)
    

    实际思路如下:使用 stackmap

    java

    方法一:单调栈
    我们可以忽略数组 nums1,先对将 nums2 中的每一个元素,求出其下一个更大的元素。随后对于将这些答案放入哈希映射(HashMap)中,再遍历数组 nums1,并直接找出答案。对于 nums2,我们可以使用单调栈来解决这个问题。

    我们首先把第一个元素 nums2[1] 放入栈,随后对于第二个元素 nums2[2],如果 nums2[2] > nums2[1],那么我们就找到了 nums2[1] 的下一个更大元素 nums2[2],此时就可以把 nums2[1] 出栈并把 nums2[2] 入栈;如果 nums2[2] <= nums2[1],我们就仅把 nums2[2] 入栈。对于第三个元素 nums2[3],此时栈中有若干个元素,那么所有比 nums2[3] 小的元素都找到了下一个更大元素(即 nums2[3]),因此可以出栈,在这之后,我们将 nums2[3] 入栈,以此类推。

    可以发现,我们维护了一个单调栈,栈中的元素从栈顶到栈底是单调不降的。当我们遇到一个新的元素 nums2[i] 时,我们判断栈顶元素是否小于 nums2[i],如果是,那么栈顶元素的下一个更大元素即为 nums2[i],我们将栈顶元素出栈。重复这一操作,直到栈为空或者栈顶元素大于 nums2[i]。此时我们将 nums2[i] 入栈,保持栈的单调性,并对接下来的 nums2[i + 1], nums2[i + 2] ... 执行同样的操作。

    作者:LeetCode
    链接:https://leetcode-cn.com/problems/next-greater-element-i/solution/xia-yi-ge-geng-da-yuan-su-i-by-leetcode/
    来源:力扣(LeetCode)
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

    class Solution {
        public int[] nextGreaterElement(int[] nums1, int[] nums2) {
            Stack<Integer> stack = new Stack<>();
            //map<aNumLeft, aNumBiggerThanaNumLeft>
            Map<Integer, Integer> map = new HashMap<>();
            int[] ret = new int[nums1.length];
            // tt 每个nums 里的元素,依次将会放入一个单调下降stack
            // tt 每次准备放入nums[x] 的时候,检查stack top 的元素,如果
            // tt 小于即将进入的nums[x] 那么就会pop stack top,并放入map 
            for (int num : nums2) {
                while(!stack.isEmpty() && stack.peek() < num) {
                    map.put(stack.pop(), num);
                }
                stack.push(num);
            }
            // tt deal with all the big ones left in our stack
            while(!stack.isEmpty()) {
                map.put(stack.pop(), -1);
            }
            for (int i = 0; i < nums1.length; i++) {
                ret[i] = map.get(nums1[i]);
            }
            return ret;
        }
    }
    /*
    执行用时 :
    6 ms
    , 在所有 Java 提交中击败了
    41.98%
    的用户
    内存消耗 :
    39.7 MB
    , 在所有 Java 提交中击败了
    5.04%
    的用户
    */
    

    another java

    class Solution {
        public int[] nextGreaterElement(int[] nums1, int[] nums2) {
            Stack<Integer> stack = new Stack<Integer>();
            HashMap<Integer, Integer> hasMap = new HashMap<Integer, Integer>();
            
            int[] result = new int[nums1.length];
            
            for(int num : nums2) {
                while(!stack.isEmpty() && stack.peek()<num){
                    hasMap.put(stack.pop(), num);
                }
                stack.push(num);
            }
            
            for(int i = 0; i < nums1.length; i++) result[i] = hasMap.getOrDefault(nums1[i], -1);
                
            return result;
        }
    }
    
  • 相关阅读:
    VMware Workstation Pro 12 创建虚拟机(安装Ubuntu)
    老师的题目(开心一刻)
    政务私有云盘系统建设的工具 – Mobox私有云盘
    学校信息化分享-中小学怎样快速完成教学资源库的建设
    SpringBoot 2.x 文件上传出现 The field file exceeds its maximum permitted size of 1048576 bytes
    nginx错误集
    nginx做http强制跳转https,接口的POST请求变成GET
    swagger Base URL地址和下边的不一致
    CentOS7关闭防火墙
    nginx配置:静态访问txt文件
  • 原文地址:https://www.cnblogs.com/paulkg12/p/12368957.html
Copyright © 2011-2022 走看看