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

📅  最后修改于: 2021-09-08 12:32:23             🧑  作者: Mango

给定两个数字K、X和一个包含 N 个整数的数组arr[] ,任务是找到最长子数组的长度,使其包含最多 ‘K’ 次出现的整数 ‘X’。
例子:

朴素的方法:这个问题的朴素的方法是为给定的子数组生成所有可能的子数组。然后,对于每个子数组,找到包含元素X最多出现K次的最大子数组。这种方法的时间复杂度为O(N 2 ) ,其中 N 是数组中的元素数。
Efficient Approach:解决这个问题的思路是使用二指针技术。

  • 将两个指针 ‘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


Javascript


输出:
5

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

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