✅ 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;
}
}

lc 0226的更多相关文章

  1. 四种比较简单的图像显著性区域特征提取方法原理及实现-----> AC/HC/LC/FT。

    laviewpbt  2014.8.4 编辑 Email:laviewpbt@sina.com   QQ:33184777 最近闲来蛋痛,看了一些显著性检测的文章,只是简单的看看,并没有深入的研究,以 ...

  2. “LC.exe”错误

    错误“LC.exe”已退出,代码为 -1. 可能的原因是: 这个第三方组件是个商业组件,他在组件的主使用类定义了 LicenseProvider(typeof(LicFileLicenseProvid ...

  3. 解决VS下“LC.exe已退出,代码为-1”问题

    今天使用VS2015开发一个Winform程序,手一抖拖错了一个第三方控件,然后将其去掉并删除相关的引用,结果导致了LC.exe错误:"Lc.exe已退出,代码为-1 ". 经过上 ...

  4. 解析.NET 许可证编译器 (Lc.exe) 的原理与源代码剖析

    许可证编译器 (Lc.exe) 的作用是读取包含授权信息的文本文件,并产生一个可作为资源嵌入到公用语言运行库可执行文件中的 .licenses 文件. 在使用第三方类库时,经常会看到它自带的演示程序中 ...

  5. Lc.exe已退出,代码为-1

    编译项目,出现提示"Lc.exe已退出,代码为-1" .   解决办法: 意思就是把licenses.licx这个文件里的内容删除,但是文件还在(此时是个空文件),发生这个问题的原 ...

  6. "LC.exe" exited with code -1 错误

    当打开一个VS程序时出现"LC.exe" exited with code -1错误,解决方法是: 删除licenses.licx文件即可

  7. LC.exe exited with code -1

    昨天从win8.1升级到win10之后, 一切还算顺利, 就是升级时间比较长. 但是快下班的时候 遇到一个问题, 是之前在win8.1上没遇到的, 首先代码win8.1 vs2013 上跑的时候一切正 ...

  8. vs2012编译出错“LC.exe”已退出解决方法

    “LC.exe”已退出,代码为 -1. 解决方法: 将项目Properties下的licenses.licx文件删除,重新编译即可.

  9. TT付款方式、前TT和后TT、LC信用证+TT付款方式

    TT付款方式是以外汇现金方式结算,由您的客户将款项汇至贵公司指定的外汇银行账号内,可以要求货到后一定期限内汇款. .T/T属于商业信用,也就是说付款的最终决定权在于客户.T/T分预付,即期和远期.现在 ...

随机推荐

  1. 十大常见web漏洞及防范

    十大常见web漏洞 一.SQL注入漏洞 SQL注入攻击(SQL Injection),简称注入攻击.SQL注入,被广泛用于非法获取网站控制权,是发生在应用程序的数据库层上的安全漏洞.在设计程序,忽略了 ...

  2. C#学习笔记之泛型

    泛型的作用和约定 提高性能 拆箱和装箱 从值类型转换为引用类型为装箱,把引用类型转换为值类型为拆箱 装箱和拆箱很容易使用,但是性能损失比较大,尤其是遍历许多项的时候. List<T>不使用 ...

  3. Codeforces Round #567 (Div. 2) A.Chunga-Changa

    原文链接:传送 #include"algorithm" #include"iostream" #include"cmath" using n ...

  4. hive导出数据到本地文件报错解决方法

    报错信息: Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.MoveTask. Unable to move so ...

  5. JS高级---为内置对象添加原型方法

    为内置对象添加原型方法 我们能否为系统的对象的原型中添加方法, 相当于在改变源码   我希望字符串中有一个倒序字符串的方法 //我希望字符串中有一个倒序字符串的方法 String.prototype. ...

  6. 普及C组第二题(8.2)

    1340. [南海2009初中]jumpcow(牛跳) (Standard IO) 题目: John的奶牛们计划要跳到月亮上去.它们请魔法师配制了 P (1 <= P <=150,000) ...

  7. Codeforces 1315C Restoring Permutation

    You are given a sequence b1,b2,…,bnb1,b2,…,bn . Find the lexicographically minimal permutation a1,a2 ...

  8. 【音乐欣赏】《Siren》 - The Chainsmokers / Aazar

    曲名:Siren 作者:The Chainsmokers . Aazar [00:00.00] 作曲 : Alex Pall/Andrew Taggart/Alexis Duvivier [00:01 ...

  9. 【音乐欣赏】《Sunflower》 - Post Malone / Swae Lee

    曲名:Sunflower 作者:Post Malone.Swae Lee [00:02.29]Ayy, ayy, ayy, ayy (ooh) [00:09.49]Ooh, ooh, ooh, ohh ...

  10. 每日扫盲(五):RPC(Remote Procedure Call)

    作者:洪春涛链接:https://www.zhihu.com/question/25536695/answer/221638079来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注 ...