给定一个由前N 个自然数组成的数组arr[] ,使用数组元素构造一个无向图,使得对于任何数组元素,将一条边与左侧和右侧的下一个更大的元素连接起来。
例子:
Input: arr = {1, 2, 3, 4, 5}
Output: No
Explanation:
It is clear from the below image that final graph will be a tree.
Input: arr[] = {1, 4, 2, 5, 3}
Output: Yes
朴素的方法:最简单的方法是使用上述条件构建所需的图,并检查是否存在至少长度为 3 的循环。如果存在循环,则打印“是”。否则,打印“否”。
时间复杂度: O(N + E),其中 E 是边数。
辅助空间: O(N)
有效的方法:最佳的想法是检查给定的排列是单峰的还是非单峰的,即简单地检查是否存在任何数组元素的两侧具有更大的相邻元素。如果发现是真的,打印“是”。否则,打印“否”。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to check if the graph
// constructed from given array
// contains a cycle or not
void isCycleExists(int arr[], int N)
{
bool valley = 0;
// Traverse the array
for (int i = 1; i < N; i++) {
// If arr[i] is less than
// arr[i - 1] and arr[i]
if (arr[i] < arr[i - 1]
&& arr[i] < arr[i + 1]) {
cout << "Yes" << endl;
return;
}
}
cout << "No";
}
// Driver Code
int main()
{
// Given array
int arr[] = { 1, 3, 2, 4, 5 };
// Size of the array
int N = sizeof(arr)
/ sizeof(arr[0]);
isCycleExists(arr, N);
return 0;
}
Java
// Java program for the above approach
import java.io.*;
class GFG
{
// Function to check if the graph
// constructed from given array
// contains a cycle or not
static void isCycleExists(int[] arr, int N)
{
// Traverse the array
for (int i = 1; i < N; i++)
{
// If arr[i] is less than
// arr[i - 1] and arr[i]
if (arr[i] < arr[i - 1]
&& arr[i] < arr[i + 1])
{
System.out.println("Yes");
return;
}
}
System.out.println("No");
}
// Driver Code
public static void main(String[] args)
{
// Given array
int[] arr = { 1, 3, 2, 4, 5 };
// Size of the array
int N = arr.length;
isCycleExists(arr, N);
}
}
// This code is contributed by Dharanendra L V.
Python3
# Python3 program for the above approach
# Function to check if the graph
# constructed from given array
# contains a cycle or not
def isCycleExists(arr, N):
valley = 0
# Traverse the array
for i in range(1, N):
# If arr[i] is less than
# arr[i - 1] and arr[i]
if (arr[i] < arr[i - 1] and arr[i] < arr[i + 1]):
print("Yes")
return
print("No")
# Driver Code
if __name__ == '__main__':
# Given array
arr = [1, 3, 2, 4, 5]
# Size of the array
N = len(arr)
isCycleExists(arr, N)
# This code is contributed by mohit kumar 29
C#
// C# program for the above approach
using System;
class GFG
{
// Function to check if the graph
// constructed from given array
// contains a cycle or not
static void isCycleExists(int[] arr, int N)
{
// Traverse the array
for (int i = 1; i < N; i++)
{
// If arr[i] is less than
// arr[i - 1] and arr[i]
if (arr[i] < arr[i - 1]
&& arr[i] < arr[i + 1])
{
Console.WriteLine("Yes");
return;
}
}
Console.WriteLine("No");
}
// Driver Code
public static void Main()
{
// Given array
int[] arr = { 1, 3, 2, 4, 5 };
// Size of the array
int N = arr.Length;
isCycleExists(arr, N);
}
}
// This code is contributed by chitranayal.
输出:
Yes
时间复杂度: O(N)
辅助空间: O(1)
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live