📌  相关文章
📜  检查是否可以选择三个建筑物,使第三个建筑物高于第一个建筑物并小于第二个建筑物

📅  最后修改于: 2021-09-06 11:12:54             🧑  作者: Mango

给定一个由N 个整数组成的数组arr[] ,其中每个数组元素代表位于X坐标上的建筑物的高度,任务是检查是否可以选择3 个建筑物,这样第三个选定的建筑物是比第一个选定的建筑物高,比第二个选定的建筑物矮。

例子:

方法:可以使用堆栈数据结构解决给定的问题。请按照以下步骤解决问题:

  • 如果N小于3 ,则打印“”。
  • 初始化一个数组,比如preMin[],来存储数组arr[]前缀最小数组
  • 遍历数组arr[]并将preMin[i]更新为preMin[i] = min(preMin[i-1], arr[i])。
  • 现在,初始化一个堆栈,比如说堆栈,以从结尾开始按升序存储元素。
  • 使用变量i反向遍历数组arr[] 并执行以下步骤:
    • 如果arr[i]大于preMin[i],则执行以下操作:
      • 不为空且栈顶元素小于preMin[i]时进行迭代然后在每次迭代中弹出栈顶元素。
      • 如果不为空且栈顶元素小于arr[i],则打印“ Yes ”并返回。
      • 否则,在上述步骤之后,将arr[i]压入堆栈
  • 完成上述步骤后,如果以上情况都不满足,则打印“”。

下面是上述方法的实现:

C++
// C++ implementation of the above approach
#include 
using namespace std;
 
// Function to check if it is possible
// to select three buildings that
// satisfy the given condition
string recreationalSpot(int arr[], int N)
{
 
    if (N < 3) {
        return "No";
    }
 
    // Stores prefix min array
    int preMin[N];
    preMin[0] = arr[0];
 
    // Iterate over the range [1, N-1]
    for (int i = 1; i < N; i++) {
        preMin[i] = min(preMin[i - 1], arr[i]);
    }
 
    // Stores the element from the
    // ending in increasing order
    stack stack;
 
    // Iterate until j is greater than
    // or equal to 0
    for (int j = N - 1; j >= 0; j--) {
 
        // If current array element is
        // greater than the prefix min
        // upto j
        if (arr[j] > preMin[j]) {
 
            // Iterate while stack is not
            // empty and top element is
            // less than or equal to preMin[j]
 
            while (!stack.empty()
                   && stack.top() <= preMin[j]) {
                // Remove the top element
                stack.pop();
            }
 
            // If stack is not empty and top
            // element of the stack is less
            // than the current element
            if (!stack.empty() && stack.top() < arr[j]) {
                return "Yes";
            }
            // Push the arr[j] in stack
            stack.push(arr[j]);
        }
    }
    // If none of the above case
    // satify then return "No"
    return "No";
}
 
// Driver code
int main()
{
    // Input
    int arr[] = { 4, 7, 11, 5, 13, 2 };
    int size = sizeof(arr) / sizeof(arr[0]);
 
    cout << recreationalSpot(arr, size);
}


Java
// Java implementation of the above approach
import java.io.*;
import java.util.*;
 
class GFG{
 
// Function to check if it is possible
// to select three buildings that
// satisfy the given condition
static String recreationalSpot(int arr[], int N)
{
    if (N < 3)
    {
        return "No";
    }
 
    // Stores prefix min array
    int preMin[] = new int[N];
    preMin[0] = arr[0];
 
    // Iterate over the range [1, N-1]
    for(int i = 1; i < N; i++)
    {
        preMin[i] = Math.min(preMin[i - 1], arr[i]);
    }
 
    // Stores the element from the
    // ending in increasing order
    Stack stack = new Stack();
 
    // Iterate until j is greater than
    // or equal to 0
    for(int j = N - 1; j >= 0; j--)
    {
         
        // If current array element is
        // greater than the prefix min
        // upto j
        if (arr[j] > preMin[j])
        {
             
            // Iterate while stack is not
            // empty and top element is
            // less than or equal to preMin[j]
            while (stack.empty() == false &&
                   stack.peek() <= preMin[j])
            {
                 
                // Remove the top element
                stack.pop();
            }
 
            // If stack is not empty and top
            // element of the stack is less
            // than the current element
            if (stack.empty() == false &&
                stack.peek() < arr[j])
            {
                return "Yes";
            }
             
            // Push the arr[j] in stack
            stack.push(arr[j]);
        }
    }
     
    // If none of the above case
    // satify then return "No"
    return "No";
}
 
// Driver code
public static void main(String[] args)
{
     
    // Input
    int arr[] = { 4, 7, 11, 5, 13, 2 };
    int size = arr.length;
 
    System.out.println(recreationalSpot(arr, size));
}
}
 
// This code is contributed by Dharanendra L V.


Python3
# Python3 implementation of the above approach
 
# Function to check if it is possible
# to select three buildings that
# satisfy the given condition
def recreationalSpot(arr, N):
     
    if (N < 3):
        return "No"
 
    # Stores prefix min array
    preMin = [0] * N
    preMin[0] = arr[0]
 
    # Iterate over the range [1, N-1]
    for i in range(1, N):
        preMin[i] = min(preMin[i - 1], arr[i])
 
    # Stores the element from the
    # ending in increasing order
    stack = []
 
    # Iterate until j is greater than
    # or equal to 0
    for j in range(N - 1, -1, -1):
         
        # If current array element is
        # greater than the prefix min
        # upto j
        if (arr[j] > preMin[j]):
 
            # Iterate while stack is not
            # empty and top element is
            # less than or equal to preMin[j]
            while (len(stack) > 0 and
                   stack[-1] <= preMin[j]):
                        
                # Remove the top element
                del stack[-1]
 
            # If stack is not empty and top
            # element of the stack is less
            # than the current element
            if (len(stack) > 0 and stack[-1] < arr[j]):
                return "Yes"
 
            # Push the arr[j] in stack
            stack.append(arr[j])
 
    # If none of the above case
    # satify then return "No"
    return "No"
 
# Driver code
if __name__ == '__main__':
     
    # Input
    arr =  [ 4, 7, 11, 5, 13, 2 ]
    size = len(arr)
 
    print (recreationalSpot(arr, size))
 
# This code is contributed by mohit kumar 29


C#
// C# implementation of the above approach
using System;
using System.Collections.Generic;
public class GFG{
 
// Function to check if it is possible
// to select three buildings that
// satisfy the given condition
static String recreationalSpot(int []arr, int N)
{
    if (N < 3)
    {
        return "No";
    }
 
    // Stores prefix min array  
    int []preMin = new int[N];
    preMin[0] = arr[0];
 
    // Iterate over the range [1, N-1]
    for(int i = 1; i < N; i++)
    {
        preMin[i] = Math.Min(preMin[i - 1], arr[i]);
    }
 
    // Stores the element from the
    // ending in increasing order
    Stack stack = new Stack();
 
    // Iterate until j is greater than
    // or equal to 0
    for(int j = N - 1; j >= 0; j--)
    {
         
        // If current array element is
        // greater than the prefix min
        // upto j
        if (arr[j] > preMin[j])
        {
             
            // Iterate while stack is not
            // empty and top element is
            // less than or equal to preMin[j]
            while (stack.Count!=0 &&
                   stack.Peek() <= preMin[j])
            {
                 
                // Remove the top element
                stack.Pop();
            }
 
            // If stack is not empty and top
            // element of the stack is less
            // than the current element
            if (stack.Count!=0 &&
                stack.Peek() < arr[j])
            {
                return "Yes";
            }
             
            // Push the arr[j] in stack
            stack.Push(arr[j]);
        }
    }
     
    // If none of the above case
    // satify then return "No"
    return "No";
}
 
// Driver code
public static void Main(String[] args)
{
     
    // Input
    int []arr = { 4, 7, 11, 5, 13, 2 };
    int size = arr.Length;
 
    Console.WriteLine(recreationalSpot(arr, size));
}
}
 
// This code is contributed by 29AjayKumar


Javascript


输出:
Yes

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

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