📌  相关文章
📜  检查是否可以通过给定操作删除所有数组元素

📅  最后修改于: 2021-04-22 07:38:13             🧑  作者: Mango

给定包含不同元素的数组arr [] ,任务是检查是否可以通过选择任意两个相邻索引来删除所有数组元素,以使arr [i] 并删除两个元素之一或每一步都一样。如果可能,请打印“是” 。否则,打印“否”
例子:

天真的方法:
想法是考虑给定数组中的所有相邻对,如果满足给定条件,则删除那些数字之一并重复此过程,直到所有元素都被删除为止。如果可能,请打印“是” 。否则,打印“否”
时间复杂度: O(N 2 )
辅助空间: O(1)
高效方法:
由于数组的元素是不同的,因此可以观察到,如果数组的第一个元素小于数组的最后一个元素,则可以删除数组的所有元素。否则,不能删除给定数组的所有元素。
请按照以下步骤解决问题:

  • 检查arr [0] ,打印“是”
  • 否则,打印“否”

下面是上述方法的实现:

C++
// C++ program to implement 
// the above approach
#include
using namespace std;
  
// Function to check if it is possible
// to remove all array elements
void removeAll(int arr[], int n)
{
  
    // Condition if we can remove
    // all elements from the array
    if (arr[0] < arr[n - 1])
        cout << "YES";
    else
        cout << "NO";
}
  
// Driver Code
int main()
{
  
    int Arr[] = { 10, 4, 7, 1, 3, 6 };
  
    int size = sizeof(Arr) / sizeof(Arr[0]);
  
    removeAll(Arr, size);
    return 0;
}


Java
// Java program to implement 
// the above approach
class GFG{
   
// Function to check if it is possible
// to remove all array elements
static void removeAll(int arr[], int n)
{
   
    // Condition if we can remove
    // all elements from the array
    if (arr[0] < arr[n - 1])
        System.out.print("YES");
    else
        System.out.print("NO");
}
   
// Driver Code
public static void main(String[] args)
{
    int Arr[] = { 10, 4, 7, 1, 3, 6 };
   
    int size = Arr.length;
   
    removeAll(Arr, size);
}
}
  
// This code is contributed by Rohit_ranjan


Python3
# Python3 program to implement  
# the above approach 
  
# Function to check if it is possible 
# to remove all array elements 
def removeAll(arr, n):
    
  # Condition if we can remove 
  # all elements from the array 
  if arr[0] < arr[n - 1]:
    print("YES")
  else:
    print("NO")
      
# Driver code
arr = [ 10, 4, 7, 1, 3, 6 ]
  
removeAll(arr, len(arr))
  
# This code is contributed by dipesh99kumar


C#
// C# program to implement 
// the above approach
using System;
  
class GFG{
  
// Function to check if it is possible
// to remove all array elements
static void removeAll(int []arr, int n)
{
  
    // Condition if we can remove
    // all elements from the array
    if (arr[0] < arr[n - 1])
        Console.Write("YES");
    else
        Console.Write("NO");
}
  
// Driver Code
public static void Main(String[] args)
{
    int []Arr = { 10, 4, 7, 1, 3, 6 };
  
    int size = Arr.Length;
  
    removeAll(Arr, size);
}
}
  
// This code is contributed by amal kumar choubey


输出:
NO

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