n个整数的无序数组,找到每个元素后面比它大的第一个数,要求时间复杂度为O(N)
package com.test.day01;
/*
@author YG
@create 2021/3/17 22:04
*/
import java.util.Stack;
public class test {
public static void main(String[] args) {
int[] a = {100,5, 3, 2, 4, 11};
int[] result = func(a);
for (int i = 0; i < a.length; i++) {
if (result[i] == -1) {
System.out.println("null");
} else {
System.out.println(a[result[i]]);
}
}
}
public static int[] func(int[] array){
int length = array.length;
Stack<Integer> stack = new Stack<Integer>();
int[] result = new int[length];
int i = 0;
while(i<length){
if(stack.isEmpty()){
stack.push(i);
i++;
continue;
}
if (array[stack.peek()]>array[i]){
stack.push(i);
i++;
continue;
}
int top = stack.pop();
result[top]=i;
}
while (!stack.isEmpty()){
int top = stack.pop();
result[top] = -1;
}
return result;
}
}
public class Main{
public static void main(String[] args) throws Exception{
int[] a = new int[]{2,1,3,2,5};
int[] ans = new int[a.length];
Stack<Integer> stack = new Stack<>();
for(int i=0;i<a.length-1;i++){
if(a[i] >= a[i+1]){
stack.push(i);
}else{
ans[i] = a[i+1];
while(!stack.isEmpty() && nums[stack.peek()] < a[i+1]){
ans[stack.peek()] = a[i+1];
stack.pop();
}
}
}
for(Integer an:ans){
System.out.println(an);
}
}
} #include <bits/stdc++.h>
using namespace std;
vector<int> find1(vector<int>num)
{
if(num.size() == 0) return {};
vector<int> res(num.size(),-1);
stack<int> s;
int i = 0;
while(i < num.size())
{
if(s.empty() || num[s.top()] >= num[i]) s.push(i++);//当前元素比栈顶元素小,加入单调栈中
else
{
res[s.top()] = num[i]; //当前元素是栈顶元素后面的第一个较大元素,加入结果中
s.pop();
}
}
return res;
}
int main()
{
vector<int> num = {1, 3, 2, 4, 99, 101, 5, 8};
vector<int> res = find1(num);
for(auto i : res)
cout << i << " ";
return 0;
} vector<int> findMax(vector<int>num)
{
if(num.size()==0)
return num;
vector<int>res(num.size());
int i=0;
stack<int>s;
while(i<num.size())
{
if(s.empty()||num[s.top()]>=num[i])
{
s.push(i++);
}
else
{
res[s.top()]=num[i];
s.pop();
}
}
while(!s.empty())
{
res[s.top()]=INT_MAX;
s.pop();
}
return res;
}