当前位置:网站首页>Monotonic stack structure
Monotonic stack structure
2022-07-24 22:14:00 【Harrison who likes to knock code】
What is a monotonous stack ?
A specially designed stack structure , In order to solve the following problems :
Given an array that may contain duplicate values arr,i The number of positions must have the following two information
- arr[i] The left side of the is away from i Recent and less than ( Or greater than )arr[i] Where is the number of ?
- arr[i] The right side of the is away from i Recent and less than ( Or greater than )arr[i] Where is the number of ?
If you want arr Two messages for all locations in , How to make the process of getting information as fast as possible .
So how to design it ?
The required time complexity is O(N)
package com.harrison.class14;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
/** * @author Harrison * @create 2022-03-26-19:03 * @motto looking for him for thousand times in the crowd , Suddenly look back , The man was in the dim light . */
public class Code01_MonotonousStack {
/* arr=[ 3, 1, 2, 3] index 0 1 2 3 return ( Record position , No, just remember -1): [ 0:[-1, 1] 1:[-1, -1] 2:[1, -1] 3:[2, -1] ] */
public static int[][] getNearLessNoRepeat(int[] arr){
int[][] res=new int[arr.length][2];
// Only subscripts are stored in the monotone stack
Stack<Integer> stack=new Stack<>();
// Traversal array arr Every number in the
for(int i=0; i<arr.length; i++){
while(!stack.isEmpty() && arr[stack.peek()]>arr[i]){
// When the current number can't fall
int j=stack.pop();
int leftLessIndex=stack.isEmpty()?-1:stack.peek();
res[j][0]=leftLessIndex;
res[j][1]=i;
}
stack.push(i);
}
while(!stack.isEmpty()){
int j=stack.pop();
int leftLessIndex=stack.isEmpty()?-1:stack.peek();
res[j][0]=leftLessIndex;
res[j][1]=-1;
}
return res;
}
public static int[][] getNearLess(int[] arr){
int[][] res=new int[arr.length][2];
Stack<List<Integer>> stack=new Stack<>();
for(int i=0; i<arr.length; i++){
while(!stack.isEmpty() && arr[stack.peek().get(0)]>arr[i]){
List<Integer> popIs=stack.pop();
int leftLessIndex=stack.isEmpty()?-1:stack.peek().get(stack.peek().size()-1);
for(Integer popi:popIs){
res[popi][0]=leftLessIndex;
res[popi][1]=i;
}
}
// If the number at this time is equal to the number at the top of the stack , Add directly to the list at the top of the stack
// If it's less than , Create a new list by yourself , Put it in the stack
if(!stack.isEmpty() && arr[stack.peek().get(0)]==arr[i]){
stack.peek().add(Integer.valueOf(i));
}else{
/* Why ArrayList without LinkedList? ArrayList Compare the value of the last position LinkedList fast LinkedList You need to go through it all ( however LinkedList Yes getLast() Method ) */
ArrayList<Integer> list=new ArrayList<>();
list.add(i);
stack.push(list);
}
}
while(!stack.isEmpty()){
List<Integer> popIs=stack.pop();
int leftLessIndex=stack.isEmpty()?-1:stack.peek().get(stack.peek().size()-1);
for(Integer popi:popIs){
res[popi][0]=leftLessIndex;
res[popi][1]=-1;
}
}
return res;
}
public static int[] getRandomArrayNoRepeat(int size){
int[] arr=new int[(int)(Math.random()*size)+1];
for(int i=0; i<arr.length; i++){
arr[i]=i;
}
for(int i=0; i<arr.length; i++){
int swapIndex=(int)(Math.random()*arr.length);
int tmp=arr[swapIndex];
arr[swapIndex]=arr[i];
arr[i]=tmp;
}
return arr;
}
public static int[] getRandomArray(int size,int max){
int[] arr=new int[(int)(Math.random()*size)+1];
for(int i=0; i<arr.length; i++){
arr[i]=(int)(Math.random()*max)-(int)(Math.random()*max);
}
return arr;
}
// Violent solution
public static int[][] rightWay(int[] arr){
int[][] res=new int[arr.length][2];
for(int i=0; i<arr.length; i++){
int leftLessIndex=-1;
int rightLessIndex=-1;
int cur=i-1;
while(cur>=0){
if(arr[cur]<arr[i]){
leftLessIndex=cur;
break;
}
cur--;
}
cur=i+1;
while(cur<arr.length){
if(arr[cur]<arr[i]){
rightLessIndex=cur;
break;
}
cur++;
}
res[i][0]=leftLessIndex;
res[i][1]=rightLessIndex;
}
return res;
}
public static boolean isEqual(int[][] res1,int[][] res2){
if(res1.length!=res2.length){
return false;
}
for(int i=0; i<res1.length; i++){
if(res1[i][0]!=res2[i][0] || res2[i][1]!=res2[i][1]){
return false;
}
}
return true;
}
public static void printArray(int[] arr){
for(int i=0; i<arr.length; i++){
System.out.print(arr[i]+" ");
}
System.out.println();
}
public static void main(String[] args) {
int size=10;
int max=20;
int testTimes=200000;
System.out.println("test begin");
for(int i=0; i<testTimes; i++){
int[] arr1=getRandomArrayNoRepeat(size);
int[] arr2=getRandomArray(size,max);
if(!isEqual(getNearLessNoRepeat(arr1),rightWay(arr1))){
System.out.println("oops");
printArray(arr1);
break;
}
if(!isEqual(getNearLess(arr2),rightWay(arr2))){
System.out.println("oops");
printArray(arr2);
break;
}
}
System.out.println("test finish");
}
}
边栏推荐
- Leetcode 102. sequence traversal of binary tree
- ESP32C3 LED PWM使用和ESP32差异说明
- In the eyes of professionals in the robot industry, what is the current situation of the robot industry?
- Available parameters of ansible Playbook
- CSF cloth simulation filtering for PCL point cloud processing (59)
- 微机原理:CPU架构详解
- Maixll dock QR code recognition
- 并查集结构
- Tencent +360+ Sogou school recruitment test + summary of knowledge points
- SVM - for linear separability (Part 2)
猜你喜欢

Get the solution to the slow running speed of Mengxin Xiaobai computer! ٩ ( ‘ ω‘ )و get! ٩ ( ‘ ω‘ )و

通过企业微信自建应用向微信推送信息

From A76 to A78 -- learning arm microarchitecture in change

有序表之AVL树

【考研英语词汇训练营】Day 11 —— offer ,form ,maintain ,critical

Circom 2.0: A Scalable Circuit Compiler

使用frp实现内网穿透

Projection regularization of line point set in PCL point cloud processing (56)

Apipost signs up with Chinatelecom! Work together to accelerate the digital transformation of enterprises

Plane regularization of PCL point cloud processing (55)
随机推荐
PCL点云处理之创建二维格网组织点云数据(六十四)
Available parameters of ansible Playbook
ASP.NET Core 6.0 基于模型验证的数据验证
[which is better to use, apopost or apifox? Just read this!]
由斐波那契数列引述到矩阵快速幂技巧
Push information to wechat through enterprise wechat self built application
Gradle learning set integration
Get the solution to the slow running speed of Mengxin Xiaobai computer! ٩ ( ‘ ω‘ )و get! ٩ ( ‘ ω‘ )و
单调栈结构练习——子数组最小值的累加和
Moving least squares fitting experiment of PCL point cloud processing (62)
Drawing library Matplotlib installation configuration
SQL语言的通用语法及分类(二)
Plane regularization of PCL point cloud processing (55)
一种兼容、更小、易用的WEB字体API
Glidemodule appglidemodule and generated API details
ASP. Net core 6.0 data validation based on model validation
10 key points and 5 measures for good project management
PCL点云处理之均匀采样抽稀(六十一)
Pyqt5 uses qfile and qdatastream to read and write binary files
Implement redis sentinel to simulate master failure scenarios