Stack
[toc]
Stack
What is a stack?
- Answer: A stack is a linear data structure that follows the Last In, First Out (LIFO) principle, where the last element added to the stack is the first one to be removed. Common operations include
push
(to add an element),pop
(to remove the top element), andpeek
(to view the top element without removing it).
- Answer: A stack is a linear data structure that follows the Last In, First Out (LIFO) principle, where the last element added to the stack is the first one to be removed. Common operations include
What are the primary operations of a stack?
Answer:
The primary operations of a stack are:
push(x)
: Add element x to the top of the stack.pop()
: Remove the element from the top of the stack.peek() or top()
: Return the top element without removing it.isEmpty()
: Return true if the stack is empty, false otherwise.
How is a stack different from a queue?
- Answer: A stack follows the LIFO (Last In, First Out) principle, where the last element added is the first to be removed. A queue follows the FIFO (First In, First Out) principle, where the first element added is the first to be removed.
232. Implement Queue using Stacks
Easy
Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (push
, peek
, pop
, and empty
).
1 | class MyQueue { |
improve:
1 | class MyQueue { |
225. Implement Stack using Queues
Easy
Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (push
, top
, pop
, and empty
).
1 | class MyStack { |
improve:
queue biting its tail
1 | //每 offer 一个数(A)进来,都重新排列,把这个数(A)放到队列的队首, notic 每字 |
232 & 255 wrap up
232 拿另外一个stack来装之前stack里面的数,这样另外这个stack里面最上面的数就是新加的数
all previous elements are removed from the stack, and the new element to be added is placed at the front of the stack.
255 把之前所有的数都拿出来,把要加的数放到最前面
all previous elements are removed from the stack, and the new element to be added is placed at the front of the stack.
20. Valid Parentheses
Easy
Given a string s
containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
- Every close bracket has a corresponding open bracket of the same type.
Example 1:
1 | Input: s = "()" |
Example 2:
1 | Input: s = "()[]{}" |
1 | class Solution { |
1047. Remove All Adjacent Duplicates In String
Easy
You are given a string s
consisting of lowercase English letters. A duplicate removal consists of choosing two adjacent and equal letters and removing them.
We repeatedly make duplicate removals on s
until we no longer can.
Return the final string after all such duplicate removals have been made. It can be proven that the answer is unique.
Example 1:
1 | Input: s = "abbaca" |
1 | class Solution { |
150. Evaluate Reverse Polish Notation
Medium
You are given an array of strings tokens
that represents an arithmetic expression in a Reverse Polish Notation.
Evaluate the expression. Return an integer that represents the value of the expression.
Note that:
- The valid operators are
'+'
,'-'
,'*'
, and'/'
. - Each operand may be an integer or another expression.
- The division between two integers always truncates toward zero.
- There will not be any division by zero.
- The input represents a valid arithmetic expression in a reverse polish notation.
- The answer and all the intermediate calculations can be represented in a 32-bit integer.
Example 1:
1 | Input: tokens = ["2","1","+","3","*"] |
1 | class Solution { |
In my initial attempt, I mistakenly converted the tokens array into a char array, which was incorrect.
wrap up the application of using stack
- Deal with Nesting: Like checking if parentheses or brackets are balanced, or navigating nested structures like folders in a directory.
Need to Explore Possibilities: For example, finding a path through a maze or searching for solutions in a game.
Manage Function Calls or Recursion: When you’re evaluating expressions, tracking function calls, or handling undo/redo actions.
Handle Parsing or Syntax Checking: Such as converting expressions between different formats or making sure they follow the right rules.
Keep Track of State or History: Like tracking your browsing history or managing the state of a game.
239. Sliding Window Maximum
😭Hard
You are given an array of integers nums
, there is a sliding window of size k
which is moving from the very left of the array to the very right. You can only see the k
numbers in the window. Each time the sliding window moves right by one position.
Return the max sliding window.
Example 1:
1 | Input: nums = [1,3,-1,-3,5,3,6,7], k = 3 |
https://www.bilibili.com/video/BV1XS4y1p7qj/?vd_source=7cf01a4cc731f5d6335bce33c114b60c
1 |
|
max heap: 元素加进来,顺序会改变,所以不可以用
min heap: 元素加进来,顺序会改变,所以不可以用
monotonic queue (单调队列)
add: 如果要加的数比myque尾巴上的数大,那就把尾巴上比 要add的数 小的数全部移掉
poll: 如果要移除的数和myque最前面的数字一样,那就把myque最前面的数移除掉,否则就不管。
为什么这么做?因为我们想把不会出现在答案里的数趁早给remove掉。这样myque的最前面永远是最大的。
347. Top K Frequent Elements
😭Medium
Given an integer array nums
and an integer k
, return the k
most frequent elements. You may return the answer in any order.
Example 1:
1 | Input: nums = [1,1,1,2,2,3], k = 2 |
1 | /*Comparator接口说明: |
n log k
✨ how to loop a hashmap
1 | Map<Integer, String> map = new HashMap<>(); |
✨ min heap and max heap
1 |
|
wrap up 6/5/2024
- 统计元素出现的频率,这一类的问题可以使用map来进行统计。
对频率进行排序,这里我们可以使用一种 容器适配器就是 PriorityQue。
- use max heap/ min heap to sort multi dimension array
PriorityQueue<int[]>
this data structure is good at get the most/least frequently occuring elements in the set.
3.
In Java, the Deque
, PriorityQueue
, Queue
, and Stack
classes and interfaces share several methods, ensuring a consistent and predictable interface for common operations like adding, removing, and examining elements. Here’s a summary of how these methods align across these different data structures:
Common Methods Across Deque
, PriorityQueue
, and Queue
add(E e)
: Inserts the specified element into the queue/deque.offer(E e)
: Inserts the specified element into the queue/deque if possible.remove()
: Retrieves and removes the head of the queue/deque.poll()
: Retrieves and removes the head of the queue/deque, or returnsnull
if empty.element()
: Retrieves, but does not remove, the head of the queue/deque.peek()
: Retrieves, but does not remove, the head of the queue/deque, or returnsnull
if empty.
Methods Specific to Deque
addFirst(E e)
: Inserts the specified element at the front of the deque.addLast(E e)
: Inserts the specified element at the end of the deque.pollFirst()
: Retrieves and removes the first element, or returnsnull
if empty.pollLast()
: Retrieves and removes the last element, or returnsnull
if empty.removeFirst()
: Retrieves and removes the first element, throwsNoSuchElementException
if empty.removeLast()
: Retrieves and removes the last element, throwsNoSuchElementException
if empty.push(E e)
: Pushes an element onto the stack represented by the deque.pop()
: Pops an element from the stack represented by the deque.
Methods Specific to PriorityQueue
comparator()
: Returns the comparator used to order the elements in this queue, ornull
if the queue uses the natural ordering of its elements.
Methods Specific to Stack
push(E e)
: Pushes an element onto the stack.pop()
: Removes and returns the element at the top of the stack.peek()
: Returns the element at the top of the stack without removing it.empty()
: Tests if the stack is empty.
Summary
Java’s Deque
, PriorityQueue
, Queue
, and Stack
share several common methods that facilitate standard queue and stack operations. The Deque
interface extends Queue
, adding methods for stack-like behavior (e.g., push()
, pop()
, addFirst()
, addLast()
), whereas PriorityQueue
provides priority-based ordering. The Stack
class has methods specifically tailored for stack operations. This uniformity in method names and functionality across these collections simplifies their usage and enhances code readability and maintainability.
4o