📌  相关文章
📜  最小子数组,以使所有元素都大于K

📅  最后修改于: 2021-06-26 10:31:45             🧑  作者: Mango

给定一个由N个整数和数字K组成的数组,任务是查找所有元素都大于K的最小子数组的长度。如果没有这样的子数组,则打印-1。
例子:

方法:任务是找到所有元素都大于K的最小子数组。由于最小子数组的大小可以为1。因此,只需检查数组中是否存在任何大于K的元素。如果是,则打印“ 1”,否则打印“ -1”。
下面是上述方法的实现:

C++
// C++ program to print the length of the shortest
// subarray with all elements greater than X
#include 
using namespace std;
 
// Function to return shortest array
int smallestSubarray(int a[], int n, int x)
{
    int count = 0, length = 0;
 
    // Iterate in the array
    for (int i = 0; i < n; i++) {
 
        // check if array element
        // greater then X or not
        if (a[i] > x) {
            return 1;
        }
    }
 
    return -1;
}
 
// Driver Code
int main()
{
    int a[] = { 1, 22, 3 };
    int n = sizeof(a) / sizeof(a[0]);
    int k = 13;
 
    cout << smallestSubarray(a, n, k);
 
    return 0;
}


Java
//  Java program to print the length of the shortest
// subarray with all elements greater than X
 
import java.io.*;
 
class GFG {
 
// Function to return shortest array
static int smallestSubarray(int a[], int n, int x)
{
    int count = 0, length = 0;
 
    // Iterate in the array
    for (int i = 0; i < n; i++) {
 
        // check if array element
        // greater then X or not
        if (a[i] > x) {
            return 1;
        }
    }
 
    return -1;
}
 
// Driver Code
    public static void main (String[] args) {
    int a[] = { 1, 22, 3 };
    int n = a.length;
    int k = 13;
 
    System.out.println(smallestSubarray(a, n, k));
            }
}
// This code has been contributed by anuj_67..


Python3
# Python 3 program to print the
# length of the shortest subarray
# with all elements greater than X
 
# Function to return shortest array
def smallestSubarray(a, n, k):
     
    # Iterate in the array
    for i in range(n):
 
        # check if array element
        # greater then X or not
        if a[i] > k:
            return 1
    return -1
 
# Driver Code
a = [1, 22, 3]
n = len(a)
k = 13
print(smallestSubarray(a, n, k))
 
# This code is contributed
# by Shrikant13


C#
using System;
 
class GFG
{
     
// Function to return shortest array
static int smallestSubarray(int []a,
                            int n, int x)
{
 
    // Iterate in the array
    for (int i = 0; i < n; i++)
    {
 
        // check if array element
        // greater then X or not
        if (a[i] > x)
        {
            return 1;
        }
    }
 
    return -1;
}
 
// Driver Code
static public void Main ()
{
    int []a = { 1, 22, 3 };
    int n = a.Length;
    int k = 13;
     
    Console.WriteLine(smallestSubarray(a, n, k));
}
}
 
// This code is contributed by ajit


PHP
 $x)
        {
            return 1;
        }
    }
 
    return -1;
}
 
// Driver Code
$a = array( 1, 22, 3 );
$n = sizeof($a);
$k = 13;
 
echo smallestSubarray($a, $n, $k);
 
// This code is contributed by ajit
?>


Javascript


输出:
1

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

如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。