This note includes multiple leetcode algorithm problems we discuss in Coding Gym at 10/31, including topic:
- Stack & Queue
- Monotonicity
- Tree
- Heap
1. Min Stack
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
Implement the MinStack
class:
MinStack()
initializes the stack object.void push(int val)
pushes the elementval
onto the stack.void pop()
removes the element on the top of the stack.int top()
gets the top element of the stack.int getMin()
retrieves the minimum element in the stack.
You must implement a solution with O(1)
time complexity for each function.
Example 1:
1 | Input |
Constraints:
-231 <= val <= 231 - 1
- Methods
pop
,top
andgetMin
operations will always be called on non-empty stacks. - At most
3 * 104
calls will be made topush
,pop
,top
, andgetMin
.
My Solution
1 | var MinStack = function() { |
2. Next Greater Element I
The next greater element of some element x
in an array is the first greater element that is to the right of x
in the same array.
You are given two distinct 0-indexed integer arrays nums1
and nums2
, where nums1
is a subset of nums2
.
For each 0 <= i < nums1.length
, find the index j
such that nums1[i] == nums2[j]
and determine the next greater element of nums2[j]
in nums2
. If there is no next greater element, then the answer for this query is -1
.
Return an array ans
of length nums1.length
such that ans[i]
is the next greater element as described above.
Example 1:
1 | Input: nums1 = [4,1,2], nums2 = [1,3,4,2] |
Example 2:
1 | Input: nums1 = [2,4], nums2 = [1,2,3,4] |
Constraints:
1 <= nums1.length <= nums2.length <= 1000
0 <= nums1[i], nums2[i] <= 104
- All integers in
nums1
andnums2
are unique. - All the integers of
nums1
also appear innums2
.
Follow up: Could you find an O(nums1.length + nums2.length)
solution?
My Solution
1 | /** |
3. Daily Temperatures
Given an array of integers temperatures
represents the daily temperatures, return an array answer
such that answer[i]
is the number of days you have to wait after the ith
day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0
instead.
Example 1:
1 | Input: temperatures = [73,74,75,71,69,72,76,73] |
Example 2:
1 | Input: temperatures = [30,40,50,60] |
Example 3:
1 | Input: temperatures = [30,60,90] |
Constraints:
1 <= temperatures.length <= 105
30 <= temperatures[i] <= 100
My Solution
1 | /** |
- 本文作者: Depasinre
- 本文链接: https:/Depasinre.github.io/2024/11/01/10-31-Coding-Gym/
- 版权声明: 本博客所有文章除特别声明外,均采用 MIT 许可协议。转载请注明出处!