当前位置: 首页 > news >正文

数据结构-单调栈

给定一个不含有重复值的数组arr,找到每一个i位置左边和右边离i位置最近且值比arr[i]小的位置。返回所有位置相应的信息。


import java.util.Stack;public class MonotonousStack {public static void main(String[] args) {int arr[] = {1,2,3,9,8,7,5,6,4};int res[][] = getNearLessNoRepeat(arr);for (int i = 0; i < res.length; i++) {System.out.println(res[i][0]+"  "+res[i][1]);}System.out.println("===================");int arr2[] = {1,6,3,9,5,8,7,5,2,6,4};int res2[][] = getNearLessRepeat(arr2);for (int i = 0; i < res2.length; i++) {System.out.println(res2[i][0]+"  "+res2[i][1]);}}// 数组不包含重复值public static int[][] getNearLessNoRepeat(int arr[]){int[][] res = new int[arr.length][2];// 栈存放的是数组arr的位置索引Stack<Integer> stack = new Stack<>();for (int i =0; i < arr.length; i++){while(!stack.isEmpty() && arr[stack.peek()] > arr[i]){// 当栈顶元素比arr[i]大时,就弹出栈int popIndex = stack.pop();int leftLessIndex = stack.isEmpty() ? -1 : stack.peek();res[popIndex][0] = leftLessIndex;res[popIndex][1] = i;}stack.push(i);}// 当stack不为空时while(!stack.isEmpty()){int popIndex = stack.pop();int leftLessIndex = stack.isEmpty() ? -1 : stack.peek();res[popIndex][0] = leftLessIndex;res[popIndex][1] = -1;}return res;}// 数组包含重复值public static int[][] getNearLessRepeat(int arr[]){int[][] res = new int[arr.length][2];Stack<Integer> stack = new Stack<>();for (int i =0; i < arr.length; i++){while(!stack.isEmpty() && arr[stack.peek()] >= arr[i]){// 当栈顶元素>=arr[i]时,就弹出栈int popIndex = stack.pop();int leftLessIndex = stack.isEmpty() ? -1 : stack.peek();res[popIndex][0] = leftLessIndex;res[popIndex][1] = i;}stack.push(i);}// 当stack不为空时while(!stack.isEmpty()){int popIndex = stack.pop();int leftLessIndex = stack.isEmpty() ? -1 : stack.peek();res[popIndex][0] = leftLessIndex;res[popIndex][1] = -1;}for (int i = res.length-1; i >= 0; i--) {int index = res[i][1];if(index != -1 && arr[i] == arr[index]){res[i][1] = res[index][1];}}return res;}
}

http://www.mrgr.cn/news/5896.html

相关文章:

  • 视频美颜SDK与直播美颜工具的开发详解与技术优化
  • Llama 3.1 70B与Mistral Large 2 128B深度对比
  • MATLAB CSF布料模拟滤波分类地面点和地物点(71)
  • Tauri简介
  • Docker离线安装
  • Swift 6.0 如何更优雅的抛出和处理特定类型的错误
  • Android 14适配
  • C# 使用M2Mqtt库开发MQTT通信协议
  • 3种将4K视频转换成1080P格式的无损方法
  • 力扣刷题之3148.矩阵的最大得分
  • C# --- 深入学习类(class)
  • Python生成JMeter测试脚本----生成测试脚本并运行
  • Java ArrayList和LinkedList
  • 如何把huggingface格式的whisper模型转为openai格式
  • Git克隆仓库太大导致拉不下来的解决方法 fatal: fetch-pack: invalid index-pack output
  • HDFS回收站-删除策略详解
  • 自动控制——用描述函数法分析非线性系统的稳定性与自激振荡
  • 健康减调攻略:1月轻松掉十斤
  • 设计模式 - 责任链模式
  • 探索tailwindcss多主题切换