堆栈题总结

2024-09-05 05:44
文章标签 堆栈 总结

本文主要是介绍堆栈题总结,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

堆栈题总结

    • hot100
      • 有效的括号
      • 最小栈
      • 字符串解码
      • 每日温度
      • 柱状图中最大的矩形
    • hot100
      • 数组中的第k个最大元素
      • 前k个高频元素
      • 数据流的中位数

hot100

有效的括号

题目链接:
20.有效的括号
代码:

class Solution {public boolean isValid(String s) {Deque<Character> stack = new LinkedList<>();for (int i = 0; i < s.length(); i ++) {char ch = s.charAt(i);if (ch == '(' || ch == '[' || ch == '{') {stack.push(ch);}else {if (stack.isEmpty()) {return false;}char ch1 = stack.pop();boolean flag1 = ch == ')' && ch1 != '(';boolean flag2 = ch == ']' && ch1 != '[';boolean flag3 = ch == '}' && ch1 != '{';if (flag1 || flag2 || flag3) {return false;}}}return stack.isEmpty();}
}

最小栈

题目链接:
155.最小栈
代码:

class MinStack {Stack<Integer> dataStack;Stack<Integer> minStack;public MinStack() {dataStack = new Stack<>();minStack = new Stack<>();minStack.push(Integer.MAX_VALUE);}public void push(int val) {dataStack.push(val);minStack.push(Math.min(val,minStack.peek()));}public void pop() {dataStack.pop();minStack.pop();}public int top() {return dataStack.peek();}public int getMin() {return minStack.peek();}
}

字符串解码

题目链接:
394.字符串解码
代码:

class Solution {public String decodeString(String s) {Deque<Integer> count = new LinkedList<>();Deque<String> stack = new LinkedList<>();String curr = "";int k = 0;for (char ch:s.toCharArray()) {if (Character.isDigit(ch)) {k = k*10 + (ch - '0');}else if (ch == '[') {count.push(k);k = 0;stack.push(curr);curr = "";}else if (ch == ']') {StringBuilder tmp = new StringBuilder(stack.pop());int repeat = count.pop();for (int i = 0; i < repeat; i ++) {tmp.append(curr);}curr = tmp.toString();}else {curr += ch;}}return curr;}
}

每日温度

题目链接:
739.每日温度
代码:

class Solution {public int[] dailyTemperatures(int[] temperatures) {int n = temperatures.length;int[] res = new int[n];Deque<Integer> stack = new LinkedList<>();stack.push(0);for (int i = 1; i < n; i ++){if (temperatures[i] <= temperatures[stack.peek()]){stack.push(i);}else{while(!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]){res[stack.peek()] = i - stack.peek();stack.pop();}stack.push(i);}}return res;}
}

柱状图中最大的矩形

题目链接:
84.柱状图中最大的矩形
代码:

class Solution {public int largestRectangleArea(int[] heights) {int n = heights.length;int[] newHeights = new int[n + 2];newHeights[0] = 0;newHeights[n] = 0;for (int i = 0; i < n; i ++){newHeights[i + 1] = heights[i];}heights = newHeights;int res = 0;Deque<Integer> stack = new LinkedList<>();stack.push(0);for (int i = 1; i < heights.length; i ++){if (heights[i] > heights[stack.peek()]){stack.push(i);}else if (heights[i] == heights[stack.peek()]){stack.pop();stack.push(i);}else{while (!stack.isEmpty() && heights[i] < heights[stack.peek()]){int mid = stack.peek();stack.pop();if (!stack.isEmpty()){int left = stack.peek();int w = i - left - 1;res = Math.max(res,w*heights[mid]);}}stack.push(i);}}return res;}
}

hot100

数组中的第k个最大元素

题目链接:
215.数组中的第k个最大元素
代码:

class Solution {public void swap(int[] nums, int i, int j) {int tmp = nums[i];nums[i] = nums[j];nums[j] = tmp;}public void maxHeapify(int[] nums, int i, int heapSize){int l = 2*i + 1, r = 2*i + 2, large = i;if (l < heapSize && nums[l] > nums[large]) {large = l;}if (r < heapSize && nums[r] > nums[large]) {large = r;}if (large != i) {swap(nums, i, large);maxHeapify(nums, large, heapSize);}}public void buildHeapify(int[] nums, int heapSize) {for (int i = heapSize / 2; i >= 0; i --) {maxHeapify(nums, i, heapSize);}}public int findKthLargest(int[] nums, int k) {int heapSize = nums.length;buildHeapify(nums,heapSize);for (int i = nums.length - 1; i >= nums.length - k + 1; i --) {swap(nums, 0, i);heapSize --;maxHeapify(nums, 0, heapSize);}return nums[0];}
}

前k个高频元素

题目链接:
347.前k个高频元素
代码:

class Solution {public int[] topKFrequent(int[] nums, int k) {Map<Integer,Integer> map = new HashMap<>();for (int num: nums) {map.put(num, map.getOrDefault(num, 0) + 1);}PriorityQueue<Integer> pq = new PriorityQueue<>(new Comparator<>() {public int compare(Integer o1, Integer o2) {return map.get(o1) - map.get(o2);}});for (int entry: map.keySet()) {if (pq.size() < k) {pq.add(entry);}else {if (map.get(entry) > map.get(pq.peek())) {pq.remove();pq.add(entry);}}}int[] res = new int[k];for (int i = 0; i < k; i ++) {res[i] = pq.remove();}return res;}
}

数据流的中位数

题目链接:
295.数据流的中位数
代码:

class MedianFinder {PriorityQueue<Integer> queMin;PriorityQueue<Integer> queMax;public MedianFinder() {queMin = new PriorityQueue<>(new Comparator<Integer>() {@Overridepublic int compare(Integer o1, Integer o2) {return o2 - o1;}});queMax = new PriorityQueue<>(new Comparator<Integer>() {@Overridepublic int compare(Integer o1, Integer o2) {return o1 - o2;}});}public void addNum(int num) {if (queMin.isEmpty() || num <= queMin.peek()){queMin.add(num);if (queMax.size() + 1 < queMin.size()){queMax.add(queMin.remove());}}else{queMax.add(num);if (queMin.size() < queMax.size()){queMin.add(queMax.remove());}}}public double findMedian() {if (queMin.size() > queMax.size()) return queMin.peek();else return (queMin.peek() + queMax.peek()) / 2.0;}
}

这篇关于堆栈题总结的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1138108

相关文章

HarmonyOS学习(七)——UI(五)常用布局总结

自适应布局 1.1、线性布局(LinearLayout) 通过线性容器Row和Column实现线性布局。Column容器内的子组件按照垂直方向排列,Row组件中的子组件按照水平方向排列。 属性说明space通过space参数设置主轴上子组件的间距,达到各子组件在排列上的等间距效果alignItems设置子组件在交叉轴上的对齐方式,且在各类尺寸屏幕上表现一致,其中交叉轴为垂直时,取值为Vert

学习hash总结

2014/1/29/   最近刚开始学hash,名字很陌生,但是hash的思想却很熟悉,以前早就做过此类的题,但是不知道这就是hash思想而已,说白了hash就是一个映射,往往灵活利用数组的下标来实现算法,hash的作用:1、判重;2、统计次数;

git使用的说明总结

Git使用说明 下载安装(下载地址) macOS: Git - Downloading macOS Windows: Git - Downloading Windows Linux/Unix: Git (git-scm.com) 创建新仓库 本地创建新仓库:创建新文件夹,进入文件夹目录,执行指令 git init ,用以创建新的git 克隆仓库 执行指令用以创建一个本地仓库的

二分最大匹配总结

HDU 2444  黑白染色 ,二分图判定 const int maxn = 208 ;vector<int> g[maxn] ;int n ;bool vis[maxn] ;int match[maxn] ;;int color[maxn] ;int setcolor(int u , int c){color[u] = c ;for(vector<int>::iter

整数Hash散列总结

方法:    step1  :线性探测  step2 散列   当 h(k)位置已经存储有元素的时候,依次探查(h(k)+i) mod S, i=1,2,3…,直到找到空的存储单元为止。其中,S为 数组长度。 HDU 1496   a*x1^2+b*x2^2+c*x3^2+d*x4^2=0 。 x在 [-100,100] 解的个数  const int MaxN = 3000

状态dp总结

zoj 3631  N 个数中选若干数和(只能选一次)<=M 的最大值 const int Max_N = 38 ;int a[1<<16] , b[1<<16] , x[Max_N] , e[Max_N] ;void GetNum(int g[] , int n , int s[] , int &m){ int i , j , t ;m = 0 ;for(i = 0 ;

go基础知识归纳总结

无缓冲的 channel 和有缓冲的 channel 的区别? 在 Go 语言中,channel 是用来在 goroutines 之间传递数据的主要机制。它们有两种类型:无缓冲的 channel 和有缓冲的 channel。 无缓冲的 channel 行为:无缓冲的 channel 是一种同步的通信方式,发送和接收必须同时发生。如果一个 goroutine 试图通过无缓冲 channel

9.8javaweb项目总结

1.主界面用户信息显示 登录成功后,将用户信息存储在记录在 localStorage中,然后进入界面之前通过js来渲染主界面 存储用户信息 将用户信息渲染在主界面上,并且头像设置跳转,到个人资料界面 这里数据库中还没有设置相关信息 2.模糊查找 检测输入框是否有变更,有的话调用方法,进行查找 发送检测请求,然后接收的时候设置最多显示四个类似的搜索结果

java面试常见问题之Hibernate总结

1  Hibernate的检索方式 Ø  导航对象图检索(根据已经加载的对象,导航到其他对象。) Ø  OID检索(按照对象的OID来检索对象。) Ø  HQL检索(使用面向对象的HQL查询语言。) Ø  QBC检索(使用QBC(Qurey By Criteria)API来检索对象。 QBC/QBE离线/在线) Ø  本地SQL检索(使用本地数据库的SQL查询语句。) 包括Hibern

暑期学习总结

iOS学习 前言无限轮播图换头像网络请求按钮的configuration属性总结 前言 经过暑期培训,完成了五个项目的仿写,在项目中将零散的内容经过实践学习,有了不少收获,因此来总结一下比较重要的内容。 无限轮播图 这是写项目的第一个难点,在很多项目中都有使用,越写越熟练。 原理为制造两个假页,在首和尾分别制作最后一页和第一页的假页,当移动到假页时,使用取消动画的方式跳到