📌  相关文章
📜  检查任何长度为 M 的子数组是否连续重复至少 K 次

📅  最后修改于: 2021-09-06 05:20:02             🧑  作者: Mango

给定一个由N 个整数和两个正整数MK组成的数组arr[] ,任务是检查是否存在任何长度为M 的子数组至少连续重复K次。如果发现是真的,则打印“是” 。否则,打印“否”

例子:

朴素的方法:最简单的方法是生成所有可能的长度为M的子数组并检查每个子数组,在将它精确连接K次时是否作为给定数组中的子数组出现。如果发现是真的,则打印“是” 。否则,打印“否”

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
#include 
using namespace std;
 
// Function to check if there exists
// any subarray of length M repeating
// at least K times consecutively
bool check(int arr[], int M, int K,
           int ind)
{
    // Iterate from i equal 0 to M
    for (int i = 0; i < M; i++) {
 
        // Iterate from j equals 1 to K
        for (int j = 1; j < K; j++) {
 
            // If elements at pos + i and
            // pos + i + j * M are not equal
            if (arr[ind + i]
                != arr[ind + i + j * M]) {
 
                return false;
            }
        }
    }
    return true;
}
 
// Function to check if a subarray repeats
// at least K times consecutively or not
bool SubarrayRepeatsKorMore(
    int arr[], int N, int M, int K)
{
    // Iterate from ind equal 0 to M
    for (int ind = 0;
         ind <= N - M * K; ind++) {
 
        // Check if subarray arr[i, i + M]
        // repeats atleast K times or not
        if (check(arr, M, K, ind)) {
            return true;
        }
    }
 
    // Otherwise, return false
    return false;
}
 
// Driver Code
int main()
{
    int arr[] = { 2, 1, 2, 1, 1, 1, 3 };
    int M = 2, K = 2;
    int N = sizeof(arr) / sizeof(arr[0]);
 
    if (SubarrayRepeatsKorMore(
            arr, N, M, K)) {
        cout << "Yes";
    }
    else {
        cout << "No";
    }
 
    return 0;
}


Java
// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG{
 
// Function to check if there exists
// any subarray of length M repeating
// at least K times consecutively
static boolean check(int arr[], int M,
                     int K, int ind)
{
     
    // Iterate from i equal 0 to M
    for(int i = 0; i < M; i++)
    {
         
        // Iterate from j equals 1 to K
        for(int j = 1; j < K; j++)
        {
             
            // If elements at pos + i and
            // pos + i + j * M are not equal
            if (arr[ind + i] != arr[ind + i + j * M])
            {
                return false;
            }
        }
    }
    return true;
}
 
// Function to check if a subarray repeats
// at least K times consecutively or not
static boolean SubarrayRepeatsKorMore(int arr[], int N,
                                      int M, int K)
{
     
    // Iterate from ind equal 0 to M
    for(int ind = 0; ind <= N - M * K; ind++)
    {
         
        // Check if subarray arr[i, i + M]
        // repeats atleast K times or not
        if (check(arr, M, K, ind))
        {
            return true;
        }
    }
 
    // Otherwise, return false
    return false;
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 2, 1, 2, 1, 1, 1, 3 };
    int M = 2, K = 2;
    int N = arr.length;
 
    if (SubarrayRepeatsKorMore(arr, N, M, K))
    {
        System.out.println("Yes");
    }
    else
    {
        System.out.println("No");
    }
}
}
 
// This code is contributed by Kingash


Python3
# Python3 program for the above approach
 
# Function to check if there exists
# any subarray of length M repeating
# at least K times consecutively
def check(arr, M, K, ind):
     
    # Iterate from i equal 0 to M
    for i in range(M):
         
        # Iterate from j equals 1 to K
        for j in range(1, K, 1):
             
            # If elements at pos + i and
            # pos + i + j * M are not equal
            if (arr[ind + i] != arr[ind + i + j * M]):
                return False
 
    return True
 
# Function to check if a subarray repeats
# at least K times consecutively or not
def SubarrayRepeatsKorMore(arr, N, M, K):
     
    # Iterate from ind equal 0 to M
    for ind in range(N - M * K + 1):
         
        # Check if subarray arr[i, i + M]
        # repeats atleast K times or not
        if (check(arr, M, K, ind)):
            return True
 
    # Otherwise, return false
    return False
 
# Driver Code
if __name__ == '__main__':
     
    arr =  [2, 1, 2, 1, 1, 1, 3]
    M = 2
    K = 2
    N = len(arr)
 
    if (SubarrayRepeatsKorMore(arr, N, M, K)):
        print("Yes")
    else:
        print("No")
 
# This code is contributed by bgangwar59


C#
// C# program for the above approach
using System;
 
class GFG{
     
// Function to check if there exists
// any subarray of length M repeating
// at least K times consecutively
static bool check(int[] arr, int M, int K,
                  int ind)
{
     
    // Iterate from i equal 0 to M
    for(int i = 0; i < M; i++)
    {
         
        // Iterate from j equals 1 to K
        for(int j = 1; j < K; j++)
        {
             
            // If elements at pos + i and
            // pos + i + j * M are not equal
            if (arr[ind + i] != arr[ind + i + j * M])
            {
                return false;
            }
        }
    }
    return true;
}
 
// Function to check if a subarray repeats
// at least K times consecutively or not
static bool SubarrayRepeatsKorMore(int[] arr, int N,
                                   int M, int K)
{
     
    // Iterate from ind equal 0 to M
    for(int ind = 0; ind <= N - M * K; ind++)
    {
         
        // Check if subarray arr[i, i + M]
        // repeats atleast K times or not
        if (check(arr, M, K, ind))
        {
            return true;
        }
    }
 
    // Otherwise, return false
    return false;
}
 
// Driver code
static void Main()
{
    int[] arr = { 2, 1, 2, 1, 1, 1, 3 };
    int M = 2, K = 2;
    int N = arr.Length;
 
    if (SubarrayRepeatsKorMore(
            arr, N, M, K))
    {
        Console.WriteLine("Yes");
    }
    else
    {
        Console.WriteLine("No");
    }
}
}
 
// This code is contributed by sanjoy_62


Javascript


C++
// C++ program for the above approach
 
#include 
#include 
using namespace std;
 
// Function to check if any subarray
// of length M repeats at least
// K times consecutively or not
bool checkExists(int arr[], int N,
                 int M, int K)
{
    // Stores the required count
    // of repeated subarrays
    int count = 0;
 
    for (int i = 0; i < N - M; i++) {
 
        // Check if the next continuous
        // subarray has equal elements
        if (arr[i] == arr[i + M])
            count++;
        else
            count = 0;
 
        // Check if K continuous subarray
        // of length M are found or not
        if (count == M * (K - 1))
            return true;
    }
 
    // If no subarrays are found
    return false;
}
 
// Driver Code
int main()
{
    int arr[] = { 2, 1, 2, 1, 1, 1, 3 };
    int N = sizeof(arr) / sizeof(arr[0]);
    int M = 2, K = 2;
 
    if (checkExists(arr, N, M, K)) {
        cout << "Yes";
    }
    else {
        cout << "No";
    }
 
    return 0;
}


Java
// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG{
 
// Function to check if any subarray
// of length M repeats at least
// K times consecutively or not
static boolean checkExists(int arr[], int N,
                           int M, int K)
{
     
    // Stores the required count
    // of repeated subarrays
    int count = 0;
 
    for(int i = 0; i < N - M; i++)
    {
         
        // Check if the next continuous
        // subarray has equal elements
        if (arr[i] == arr[i + M])
            count++;
        else
            count = 0;
 
        // Check if K continuous subarray
        // of length M are found or not
        if (count == M * (K - 1))
            return true;
    }
 
    // If no subarrays are found
    return false;
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 2, 1, 2, 1, 1, 1, 3 };
    int M = 2, K = 2;
    int N = arr.length;
 
    if (checkExists(arr, N, M, K))
    {
        System.out.println("Yes");
    }
    else
    {
        System.out.println("No");
    }
}
}
 
// This code is contributed by Kingash


Python3
# Python3 program for the above approach
 
# Function to check if any subarray
# of length M repeats at least
# K times consecutively or not
def checkExists(arr, N, M, K):
     
    # Stores the required count
    # of repeated subarrays
    count = 0
 
    for i in range(N - M):
         
        # Check if the next continuous
        # subarray has equal elements
        if (arr[i] == arr[i + M]):
            count += 1
        else:
            count = 0
 
        # Check if K continuous subarray
        # of length M are found or not
        if (count == M * (K - 1)):
            return True
 
    # If no subarrays are found
    return False
 
# Driver Code
if __name__ == '__main__':
     
    arr = [ 2, 1, 2, 1, 1, 1, 3 ]
    N = len(arr)
    M = 2
    K = 2
 
    if (checkExists(arr, N, M, K)):
        print("Yes")
    else:
        print("No")
 
# This code is contributed by ipg2016107


C#
// C# program for the above approach
using System;
  
class GFG{
     
// Function to check if any subarray
// of length M repeats at least
// K times consecutively or not
public static bool checkExists(int []arr, int N,
                               int M, int K)
{
     
    // Stores the required count
    // of repeated subarrays
    int count = 0;
 
    for(int i = 0; i < N - M; i++)
    {
         
        // Check if the next continuous
        // subarray has equal elements
        if (arr[i] == arr[i + M])
            count++;
        else
            count = 0;
 
        // Check if K continuous subarray
        // of length M are found or not
        if (count == M * (K - 1))
            return true;
    }
 
    // If no subarrays are found
    return false;
}
 
// Driver Code
public static void Main()
{
    int []arr = { 2, 1, 2, 1, 1, 1, 3 };
    int N = arr.Length;
    int M = 2, K = 2;
 
    if (checkExists(arr, N, M, K))
    {
        Console.WriteLine("Yes");
    }
    else
    {
        Console.WriteLine("No");
    }
}
}
 
// This code is contributed by mohit kumar 29


Javascript


输出:
Yes

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

高效方法:上述方法可以通过使用双指针技术进行优化。请按照以下步骤解决问题:

  • 初始化一个变量,比如count as 0
  • 使用变量i在索引范围[0, N – M] 上遍历给定数组arr[] ,并执行以下步骤:
    • 如果arr[i] 的值等于arr[i + M] ,则将count增加1 ,因为子数组中有匹配项
    • 否则,将计数更新为0作为 连续子数组中存在中断。
    • 如果count 的值为M * (K – 1) ,则表示有K个连续相等的长度为M 的子数组。因此,打印“Yes”并跳出循环。
  • 完成上述步骤后,如果计数永远不会变成M * (K – 1) ,则打印“No”

下面是上述方法的实现:

C++

// C++ program for the above approach
 
#include 
#include 
using namespace std;
 
// Function to check if any subarray
// of length M repeats at least
// K times consecutively or not
bool checkExists(int arr[], int N,
                 int M, int K)
{
    // Stores the required count
    // of repeated subarrays
    int count = 0;
 
    for (int i = 0; i < N - M; i++) {
 
        // Check if the next continuous
        // subarray has equal elements
        if (arr[i] == arr[i + M])
            count++;
        else
            count = 0;
 
        // Check if K continuous subarray
        // of length M are found or not
        if (count == M * (K - 1))
            return true;
    }
 
    // If no subarrays are found
    return false;
}
 
// Driver Code
int main()
{
    int arr[] = { 2, 1, 2, 1, 1, 1, 3 };
    int N = sizeof(arr) / sizeof(arr[0]);
    int M = 2, K = 2;
 
    if (checkExists(arr, N, M, K)) {
        cout << "Yes";
    }
    else {
        cout << "No";
    }
 
    return 0;
}

Java

// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG{
 
// Function to check if any subarray
// of length M repeats at least
// K times consecutively or not
static boolean checkExists(int arr[], int N,
                           int M, int K)
{
     
    // Stores the required count
    // of repeated subarrays
    int count = 0;
 
    for(int i = 0; i < N - M; i++)
    {
         
        // Check if the next continuous
        // subarray has equal elements
        if (arr[i] == arr[i + M])
            count++;
        else
            count = 0;
 
        // Check if K continuous subarray
        // of length M are found or not
        if (count == M * (K - 1))
            return true;
    }
 
    // If no subarrays are found
    return false;
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 2, 1, 2, 1, 1, 1, 3 };
    int M = 2, K = 2;
    int N = arr.length;
 
    if (checkExists(arr, N, M, K))
    {
        System.out.println("Yes");
    }
    else
    {
        System.out.println("No");
    }
}
}
 
// This code is contributed by Kingash

蟒蛇3

# Python3 program for the above approach
 
# Function to check if any subarray
# of length M repeats at least
# K times consecutively or not
def checkExists(arr, N, M, K):
     
    # Stores the required count
    # of repeated subarrays
    count = 0
 
    for i in range(N - M):
         
        # Check if the next continuous
        # subarray has equal elements
        if (arr[i] == arr[i + M]):
            count += 1
        else:
            count = 0
 
        # Check if K continuous subarray
        # of length M are found or not
        if (count == M * (K - 1)):
            return True
 
    # If no subarrays are found
    return False
 
# Driver Code
if __name__ == '__main__':
     
    arr = [ 2, 1, 2, 1, 1, 1, 3 ]
    N = len(arr)
    M = 2
    K = 2
 
    if (checkExists(arr, N, M, K)):
        print("Yes")
    else:
        print("No")
 
# This code is contributed by ipg2016107

C#

// C# program for the above approach
using System;
  
class GFG{
     
// Function to check if any subarray
// of length M repeats at least
// K times consecutively or not
public static bool checkExists(int []arr, int N,
                               int M, int K)
{
     
    // Stores the required count
    // of repeated subarrays
    int count = 0;
 
    for(int i = 0; i < N - M; i++)
    {
         
        // Check if the next continuous
        // subarray has equal elements
        if (arr[i] == arr[i + M])
            count++;
        else
            count = 0;
 
        // Check if K continuous subarray
        // of length M are found or not
        if (count == M * (K - 1))
            return true;
    }
 
    // If no subarrays are found
    return false;
}
 
// Driver Code
public static void Main()
{
    int []arr = { 2, 1, 2, 1, 1, 1, 3 };
    int N = arr.Length;
    int M = 2, K = 2;
 
    if (checkExists(arr, N, M, K))
    {
        Console.WriteLine("Yes");
    }
    else
    {
        Console.WriteLine("No");
    }
}
}
 
// This code is contributed by mohit kumar 29

Javascript


输出:
Yes

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

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