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

📅  最后修改于: 2021-04-17 14:43:43             🧑  作者: 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


输出:
Yes

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

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

  • 初始化变量,例如count0
  • 使用变量i遍历indcies [0,N – M]范围内的给定数组arr [] ,并执行以下步骤:
    • 如果arr [i]的值等于arr [i + M] ,则由于子数组中存在匹配项,因此将count递增1
    • 否则,将计数更新为0 连续子数组中有一个中断。
    • 如果count的值为M *(K – 1) ,则意味着存在K个连续相等的长度为M的子数组。因此,打印“是”并退出循环。
  • 完成上述步骤后,如果计数永不变为M *(K – 1) ,则打印“否”

下面是上述方法的实现:

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
输出:
Yes

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