📌  相关文章
📜  找出最长的子数组的长度,其中最多出现K个整数X

📅  最后修改于: 2021-05-17 05:35:37             🧑  作者: Mango

给定两个数字K,X和包含N个整数的数组arr [] ,任务是找到最长子数组的长度,使其包含最多出现整数“ X”的“ K”个。

例子:

幼稚的方法:针对此问题的幼稚的方法是为给定的子数组生成所有可能的子数组。然后,对于每个子阵列,查找包含元素X的,最多有K发生的最大的子阵。此方法的时间复杂度为O(N 2 ) ,其中N是数组中元素的数量。

高效方法:解决此问题的想法是使用双指针技术。

  • 分别将两个指针“ i”和“ j”初始化为-1和0。
  • 继续增加“ i”。如果找到元素X,则通过保留计数器来增加该元素的计数。
  • 如果X的数量大于K,则减少数量并减小’j’的值。
  • 如果X的计数小于或等于K,则增加“ i”,并且不对“ j”进行任何更改。
  • 索引“ i”和“ j”在这里表示要考虑的子数组的起点和终点。
  • 因此,在每一步中,找到| i – j + 1 |的值。对此的最大可能值是必需的答案。

下面是上述方法的实现:

C++
// C++ program to find the length of the
// longest subarray which contains at-most
// K occurrences of the integer X
  
#include 
using namespace std;
  
// Function to find the length of the
// longest subarray  which contains at-most
// K occurrences of the integer X
int longest(int a[], int n, int k, int x)
{
    // Maximum initialized to zero
    int max = 0;
  
    // Both the pointers initialized to -1
    int i = -1;
    int j = 0;
  
    // Variable to store the count of the
    // occurrence of the element 'x'
    int m1 = 0;
  
    // Iterate through the array once
    while (i < n) {
  
        // If the count is less than equal to K
        if (m1 <= k) {
  
            // Then increase 'i'
            i++;
            if (a[i] == x) {
  
                // If the integer 'x' is found,
                // increase the count.
                m1++;
            }
        }
  
        // If the count is greater than K
        else {
  
            // If the element 'x' is found,
            // then decrease the count
            if (a[j] == x) {
                m1--;
            }
  
            // Increment the value of j.
            // This signifies that we are looking
            // at another subarray
            j++;
        }
  
// Find the maximum possible value
// among the obtained values
        if (m1 <= k && i < n) {
  
            if (abs(i - j + 1) > max) {
                max = abs(i - j + 1);
            }
        }
  
          
    }
  
    return max;
}
  
// Driver code
int main()
{
    int arr[] = { 1, 2, 2, 3, 4 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 2;
    int x = 2;
  
    cout << longest(arr, n, k, x);
  
    return 0;
}


Java
// Java program to find the length of the
// longest subarray which contains at-most
// K occurrences of the integer X
import java.util.*;
  
class GFG{
  
// Function to find the length of the
// longest subarray which contains at-most
// K occurrences of the integer X
static int longest(int a[], int n,
                   int k, int x)
{
  
    // Maximum initialized to zero
    int max = 0;
  
    // Both the pointers initialized to -1
    int i = -1;
    int j = 0;
  
    // Variable to store the count of the
    // occurrence of the element 'x'
    int m1 = 0;
  
    // Iterate through the array once
    while (i < n)
    {
  
        // If the count is less 
        // than equal to K
        if (m1 <= k)
        {
  
            // Then increase 'i'
            i++;
  
            if (i < a.length && a[i] == x)
            {
  
                // If the integer 'x' is 
                // found, increase the count.
                m1++;
            }
        }
  
        // If the count is greater than K
        else
        {
  
            // If the element 'x' is found,
            // then decrease the count
            if (j < a.length && a[j] == x)
            {
                m1--;
            }
  
            // Increment the value of j.
            // This signifies that we are 
            // looking at another subarray
            j++;
        }
          
        // Find the maximum possible value
        // among the obtained values
        if (m1 <= k && i < n)
        {
            if (Math.abs(i - j + 1) > max) 
            {
                max = Math.abs(i - j + 1);
            }
        }
    }
  
    return max;
}
  
// Driver code
public static void main(String[] args)
{
    int arr[] = { 1, 2, 2, 3, 4 };
    int n = arr.length;
    int k = 2;
    int x = 2;
  
    System.out.print(longest(arr, n, k, x));
}
}
  
// This code is contributed by Amit Katiyar


Python3
# Python3 program to find the length of the 
# longest subarray which contains at-most 
# K occurrences of the integer X 
  
# Function to find the length of the 
# longest subarray which contains at-most 
# K occurrences of the integer X 
def longest(a, n, k, x):
      
    # Maximum initialized to zero 
    max = 0; 
  
    # Both the pointers initialized to -1 
    i = -1; 
    j = 0; 
  
    # Variable to store the count of the 
    # occurrence of the element 'x' 
    m1 = 0; 
  
    # Iterate through the array once 
    while (i < n):
  
        # If the count is less than equal to K 
        if (m1 <= k):
            if (a[i] == x):
  
                # If the integer 'x' is found, 
                # increase the count. 
                m1 += 1; 
                  
            # Then increase 'i'     
            i += 1;
  
        # If the count is greater than K 
        else :
  
            # If the element 'x' is found, 
            # then decrease the count 
            if (a[j] == x):
                m1 -= 1; 
  
            # Increment the value of j. 
            # This signifies that we are looking 
            # at another subarray 
            j += 1; 
          
        # Find the maximum possible value 
        # among the obtained values 
        if (m1 <= k and i < n):
            if (abs(i - j + 1) > max):
                max = abs(i - j + 1); 
              
    return max; 
  
# Driver code 
if __name__ == "__main__" : 
  
    arr = [ 1, 2, 2, 3, 4 ]; 
    n = len(arr); 
    k = 2; 
    x = 2;
      
    print(longest(arr, n, k, x)); 
  
# This code is contributed by AnkitRai01


C#
// C# program to find the length of the
// longest subarray which contains at-most
// K occurrences of the integer X
using System;
  
class GFG{
  
// Function to find the length of the
// longest subarray which contains at-most
// K occurrences of the integer X
static int longest(int []a, int n,
                   int k, int x)
{
      
    // Maximum initialized to zero
    int max = 0;
      
    // Both the pointers initialized to -1
    int i = -1;
    int j = 0;
      
    // Variable to store the count of the
    // occurrence of the element 'x'
    int m1 = 0;
      
    // Iterate through the array once
    while (i < n)
    {
      
        // If the count is less 
        // than equal to K
        if (m1 <= k)
        {
      
            // Then increase 'i'
            i++;
              
            if (i < a.Length && a[i] == x)
            {
      
                // If the integer 'x' is 
                // found, increase the count.
                m1++;
            }
        }
      
        // If the count is greater than K
        else
        {
      
            // If the element 'x' is found,
            // then decrease the count
            if (j < a.Length && a[j] == x)
            {
                m1--;
            }
      
            // Increment the value of j.
            // This signifies that we are 
            // looking at another subarray
            j++;
        }
              
        // Find the maximum possible value
        // among the obtained values
        if (m1 <= k && i < n)
        {
            if (Math.Abs(i - j + 1) > max) 
            {
                max = Math.Abs(i - j + 1);
            }
        }
    }
      
    return max;
}
      
// Driver code
public static void Main(string[] args)
{
    int []arr = { 1, 2, 2, 3, 4 };
    int n = arr.Length;
    int k = 2;
    int x = 2;
      
    Console.WriteLine(longest(arr, n, k, x));
}
}
  
// This code is contributed by AnkitRai01


输出:
5

时间复杂度: O(N) ,其中N是数组的长度。