📌  相关文章
📜  与下一个较大元素的距离

📅  最后修改于: 2021-09-06 05:27:36             🧑  作者: Mango

给定一个大小为N的数组arr[] ,任务是打印每个数组元素与其下一个较大元素的距离。对于没有下一个更大元素的数组元素,打印 0。

例子:

朴素的方法:最简单的方法是遍历数组,对每个数组元素,向右遍历以获得其下一个更大的元素并计算索引之间的差异。

时间复杂度: O(N 2 )
辅助空间: O(1)

高效方法:为了优化上述方法,其思想是使用 Stack 来查找下一个更大的元素。
以下是步骤:

  1. 维护一个以非递增顺序包含元素的堆栈
  2. 检查当前元素arr[i]是否大于堆栈顶部的元素。
  3. 继续将栈中所有小于arr[i]的元素从栈顶取出,计算每个元素的距离,作为当前索引与被弹出元素索引的差值。
  4. 将当前元素压入栈,重复上述步骤。

下面是上述方法的实现:

C++
// C++ implementation of the
// above approach
#include
using namespace std;
 
vector mindistance(vector arr)
{
    int N = arr.size();
     
    // Stores the required distances
    vector ans(N);
    int st = 0;
     
    // Maintain a stack of elements
    // in non-increasing order
    for(int i = 0; i < N - 1; i++)
    {
        if (arr[i] < arr[i + 1])
        {
            ans[i] = 1;
        }
        else
        {
            st = i + 1;
            while (st <= N - 1)
            {
                if (arr[i] < arr[st])
                {
                    ans[i] = st - i;
                    break;
                }
                else
                {
                    st++;
                }
            }
        }
    }
    return ans;
}
 
// Driver code
int main()
{
    vector arr = { 73, 74, 75, 71,
                        69, 72, 76, 73 };
     
    vector x = mindistance(arr);
     
    cout << "[";
    for(int i = 0; i < x.size(); i++)
    {
        if (i == x.size() - 1)
            cout << x[i];
        else
          cout << x[i] << ", ";
    }
    cout << "]";
}
 
// This code is contributed by SURENDRA_GANGWAR


Java
// Java implementation of the
// above approach
import java.io.*;
 
class GFG{
     
public static int[] mindistance(int[] arr)
{
    int N = arr.length;
     
    // Stores the required distances
    int[] ans = new int[N];
    int st = 0;
     
    // Maintain a stack of elements
    // in non-increasing order
    for(int i = 0; i < N - 1; i++)
    {
        if (arr[i] < arr[i + 1])
        {
            ans[i] = 1;
        }
        else
        {
            st = i + 1;
            while (st <= N - 1)
            {
                if (arr[i] < arr[st])
                {
                    ans[i] = st - i;
                    break;
                }
                else
                {
                    st++;
                }
            }
        }
    }
    return ans;
}
 
// Driver code
public static void main(String[] args)
{
    int arr[] = new int[]{ 73, 74, 75, 71,
                           69, 72, 76, 73 };
     
    int x[] = mindistance(arr);
     
    System.out.print("[");
    for(int i = 0; i < x.length; i++)
        System.out.print(x[i]+", ");
         
    System.out.print("]");
}
}
 
// This code is contributed by sai-sampath mahajan
// and ramprasad kondoju


Python3
# Python3 implementation of the
# above approach
 
def mindistance(arr, N):
     
    if N <= 1:
        return [0]
       
    # Stores the required distances
    ans = [0 for i in range(N)]
    st = [0]
     
    # Maintain a stack of elements
    # in non-increasing order
    for i in range(1, N): 
         
        # If the current element exceeds
        # the element at the top of the stack
        while(st and arr[i] > arr[st[-1]]): 
            pos = st.pop()
            ans[pos] = i - pos
             
        # Push the current index to the stack
        st.append(i)
 
    return ans
 
# Given array
arr = [73, 74, 75, 71, 69, 72, 76, 73]
N = len(arr)
 
# Function call
print(mindistance(arr, N))


C#
// C# implementation of the
// above approach
using System;
 
class GFG{
     
public static int[] mindistance(int[] arr)
{
    int N = arr.Length;
     
    // Stores the required distances
    int[] ans = new int[N];
    int st = 0;
     
    // Maintain a stack of elements
    // in non-increasing order
    for(int i = 0; i < N - 1; i++)
    {
        if (arr[i] < arr[i + 1])
        {
            ans[i] = 1;
        }
        else
        {
            st = i + 1;
            while (st <= N - 1)
            {
                if (arr[i] < arr[st])
                {
                    ans[i] = st - i;
                    break;
                }
                else
                {
                    st++;
                }
            }
        }
    }
    return ans;
}
 
// Driver code
public static void Main(String[] args)
{
    int []arr = new int[]{ 73, 74, 75, 71,
                           69, 72, 76, 73 };
     
    int []x = mindistance(arr);
     
    Console.Write("[");
    for(int i = 0; i < x.Length; i++)
        Console.Write(x[i]+", ");
         
    Console.Write("]");
}
}
 
// This code is contributed by Amit Katiyar


Javascript


输出:
[1, 1, 4, 2, 1, 1, 0, 0]

时间复杂度: O(N)
辅助空间: O(N)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live