Algorithm 查找给定数组中每个窗口大小的最大值和最小值
给出了一个大小为N的整数数组A[],任务是找出数组中每个窗口大小的最大值和最小值。 注:窗口大小从1到n不等 例如:arr[]={10,20,30,50,10,70,30} 输出:70,30,20,10,10,10,10 我理解输出是如何产生的,但我在理解算法方面确实遇到了困难。我理解简单的方法,但涉及O(n)的解决方案非常难以理解。O(n)的代码附在下面:Algorithm 查找给定数组中每个窗口大小的最大值和最小值,algorithm,data-structures,stack,Algorithm,Data Structures,Stack,给出了一个大小为N的整数数组A[],任务是找出数组中每个窗口大小的最大值和最小值。 注:窗口大小从1到n不等 例如:arr[]={10,20,30,50,10,70,30} 输出:70,30,20,10,10,10,10 我理解输出是如何产生的,但我在理解算法方面确实遇到了困难。我理解简单的方法,但涉及O(n)的解决方案非常难以理解。O(n)的代码附在下面: import java.util.Stack; class Test { static int arr[] = {10, 20, 30
import java.util.Stack;
class Test {
static int arr[] = {10, 20, 30, 50, 10, 70, 30};
static void printMaxOfMin(int n)
{
// Used to find previous and next smaller
Stack<Integer> s = new Stack<>();
// Arrays to store previous and next smaller
int left[] = new int[n+1];
int right[] = new int[n+1];
// Initialize elements of left[] and right[]
for (int i=0; i<n; i++)
{
left[i] = -1;
right[i] = n;
}
// Fill elements of left[] using logic discussed on
// https://www.geeksforgeeks.org/next-greater-element/
for (int i=0; i<n; i++)
{
while (!s.empty() && arr[s.peek()] >= arr[i])
s.pop();
if (!s.empty())
left[i] = s.peek();
s.push(i);
}
// Empty the stack as stack is going to be used for right[]
while (!s.empty())
s.pop();
// Fill elements of right[] using same logic
for (int i = n-1 ; i>=0 ; i-- )
{
while (!s.empty() && arr[s.peek()] >= arr[i])
s.pop();
if(!s.empty())
right[i] = s.peek();
s.push(i);
}
// Create and initialize answer array
int ans[] = new int[n+1];
for (int i=0; i<=n; i++)
ans[i] = 0;
// Fill answer array by comparing minimums of all
// lengths computed using left[] and right[]
for (int i=0; i<n; i++)
{
// length of the interval
int len = right[i] - left[i] - 1;
// arr[i] is a possible answer for this length
// 'len' interval, check if arr[i] is more than
// max for 'len'
ans[len] = Math.max(ans[len], arr[i]);
}
// Some entries in ans[] may not be filled yet. Fill
// them by taking values from right side of ans[]
for (int i=n-1; i>=1; i--)
ans[i] = Math.max(ans[i], ans[i+1]);
// Print the result
for (int i=1; i<=n; i++)
System.out.print(ans[i] + " ");
}
// Driver method
public static void main(String[] args)
{
printMaxOfMin(arr.length);
} }
import java.util.Stack;
类测试{
静态int arr[]={10,20,30,50,10,70,30};
静态无效printMaxOfMin(int n)
{
//用于查找上一个和下一个较小的
堆栈s=新堆栈();
//用于存储上一个和下一个较小的
左整数[]=新整数[n+1];
右整数[]=新整数[n+1];
//初始化左[]和右[]的元素
对于(int i=0;i=0;i--)
{
而(!s.empty()&&arr[s.peek()]>=arr[i])
s、 pop();
如果(!s.empty())
右[i]=s.peek();
s、 推(i);
}
//创建并初始化应答数组
整数ans[]=新整数[n+1];
对于(inti=0;i,这可以使用一个双端队列和一个循环来完成
while q and a[end] < q[-1]:
q.pop()
q.append(a[end])
而q和a[end]
每次迭代后,q[0]将是最小值。有一个关于您链接到的部分的详细说明。您对哪些部分有困难?我很难从该方法的第二步理解@㪞עבקן