📌  相关文章
📜  长度为K的子数组,其元素被X整除

📅  最后修改于: 2021-04-24 03:44:51             🧑  作者: Mango

给定一个由N个正整数组成的数组arr [] ,任务是找到一个长度为K的子数组,使得该子数组的每个元素的连接都可以被X整除。如果不存在这样的子数组,则打印“ -1” 。如果存在多个这样的子数组,请打印其中的任何一个。

例子:

天真的方法:解决问题的最简单方法是生成所有可能的长度为K的子数组,并打印其元素的连接被X整除的子数组。如果不存在这样的子数组,则打印“ -1” 。否则,请打印这些子数组中的任何一个。

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

高效方法:可以使用滑动窗口技术来优化上述方法。请按照以下步骤解决问题:

  1. 通过串联前K个数组元素来生成数字。将其存储在变量中,例如num
  2. 检查生成的数字是否可以被X整除。如果发现为真,则打印当前子数组。
  3. 否则,遍历[K,N]范围内的数组,并对每个元素执行以下步骤:
    • 将元素arr [i]的数字添加到变量num
    • num的开头删除元素arr [i-K]数字
    • 现在检查形成的当前数字是否可以被X整除。如果发现为真,则在[i – K,i]范围内打印当前子数组。
    • 否则,请检查下一个子数组。
  4. 如果不存在这样的子数组,则打印“ -1”

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to return the starting
// index of the subarray whose
// concatenation is divisible by X
int findSubarray(vector arr,
                 int K, int X)
{
    int i, num = 0;
 
    // Generate the concatenation
    // of first K length subarray
    for (i = 0; i < K; i++) {
        num = num * 10 + arr[i];
    }
 
    // If num is divisible by X
    if (num % X == 0) {
        return 0;
    }
 
    // Traverse the remaining array
    for (int j = i; j < arr.size(); j++) {
 
        // Append the digits of arr[i]
        num = (num % (int)pow(10, j - 1))
                  * 10
              + arr[j];
 
        // If num is divisible by X
        if (num % X == 0) {
            return j - i + 1;
        }
    }
 
    // No subarray exists
    return -1;
}
 
// Function to print the subarray in
// the range [answer, answer + K]
void print(vector arr, int answer,
           int K)
{
    // No such subarray exists
    if (answer == -1) {
        cout << answer;
    }
 
    // Otherwise
    else {
 
        // Print the subarray in the
        // range [answer, answer + K]
        for (int i = answer;
             i < answer + K; i++) {
            cout << arr[i] << " ";
        }
    }
}
 
// Driver Code
int main()
{
    // Given array arr[]
    vector arr = { 1, 2, 4, 5, 9,
                        6, 4, 3, 7, 8 };
 
    int K = 4, X = 4;
 
    // Function Call
    int answer = findSubarray(arr, K, X);
 
    // Function Call to print subarray
    print(arr, answer, K);
 
    return 0;
}


Java
// Java program for the above approach
import java.io.*;
import java.util.*;
 
class GFG{
 
// Function to return the starting
// index of the subarray whose
// concatenation is divisible by X
static int findSubarray(ArrayList arr, int K,
                                                int X)
{
    int i, num = 0;
 
    // Generate the concatenation
    // of first K length subarray
    for(i = 0; i < K; i++)
    {
        num = num * 10 + arr.get(i);
    }
 
    // If num is divisible by X
    if (num % X == 0)
    {
        return 0;
    }
 
    // Traverse the remaining array
    for(int j = i; j < arr.size(); j++)
    {
         
        // Append the digits of arr[i]
        num = (num % (int)Math.pow(10, j - 1)) *
                10 + arr.get(j);
 
        // If num is divisible by X
        if (num % X == 0)
        {
            return j - i + 1;
        }
    }
 
    // No subarray exists
    return -1;
}
 
// Function to print the subarray in
// the range [answer, answer + K]
static void print(ArrayList arr, int answer,
                                          int K)
{
     
    // No such subarray exists
    if (answer == -1)
    {
        System.out.println(answer);
    }
 
    // Otherwise
    else
    {
         
        // Print the subarray in the
        // range [answer, answer + K]
        for(int i = answer; i < answer + K; i++)
        {
            System.out.print(arr.get(i) + " ");
        }
    }
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Given array arr[]
    ArrayList arr = new ArrayList(
        Arrays.asList(1, 2, 4, 5, 9, 6, 4, 3, 7, 8));
 
    int K = 4, X = 4;
 
    // Function call
    int answer = findSubarray(arr, K, X);
 
    // Function call to print subarray
    print(arr, answer, K);
}
}
 
// This code is contributed by akhilsaini


Python3
# Python3 program for the above approach
 
# Function to return the starting
# index of the subarray whose
# concatenation is divisible by X
def findSubarray(arr, K, X):
 
    num = 0
 
    # Generate the concatenation
    # of first K length subarray
    for i in range(0, K):
        num = num * 10 + arr[i]
 
    # If num is divisible by X
    if num % X == 0:
        return 0
       
    i = K
     
    # Traverse the remaining array
    for j in range(i, len(arr)):
         
        # Append the digits of arr[i]
        num = ((num % int(pow(10, j - 1))) *
                10 + arr[j])
 
        # If num is divisible by X
        if num % X == 0:
            return j - i + 1
 
    # No subarray exists
    return -1
 
# Function to print the subarray in
# the range [answer, answer + K]
def print_subarray(arr, answer, K):
     
    # No such subarray exists
    if answer == -1:
        print(answer)
 
    # Otherwise
    else:
         
        # Print the subarray in the
        # range [answer, answer + K]
        for i in range(answer, answer + K):
            print(arr[i], end = " ")
 
# Driver Code
if __name__ == "__main__":
     
    # Given array arr[]
    arr = [ 1, 2, 4, 5, 9,
            6, 4, 3, 7, 8 ]
 
    K = 4
    X = 4
 
    # Function call
    answer = findSubarray(arr, K, X)
 
    # Function call to print subarray
    print_subarray(arr, answer, K)
 
# This code is contributed by akhilsaini


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to return the starting
// index of the subarray whose
// concatenation is divisible by X
static int findSubarray(List arr, int K,
                                       int X)
{
    int i, num = 0;
 
    // Generate the concatenation
    // of first K length subarray
    for(i = 0; i < K; i++)
    {
        num = num * 10 + arr[i];
    }
 
    // If num is divisible by X
    if (num % X == 0)
    {
        return 0;
    }
 
    // Traverse the remaining array
    for(int j = i; j < arr.Count; j++)
    {
         
        // Append the digits of arr[i]
        num = (num % (int)Math.Pow(10, j - 1)) *
                10 + arr[j];
 
        // If num is divisible by X
        if (num % X == 0)
        {
            return j - i + 1;
        }
    }
     
    // No subarray exists
    return -1;
}
 
// Function to print the subarray in
// the range [answer, answer + K]
static void print(List arr, int answer,
                                 int K)
{
     
    // No such subarray exists
    if (answer == -1)
    {
        Console.WriteLine(answer);
    }
 
    // Otherwise
    else
    {
         
        // Print the subarray in the
        // range [answer, answer + K]
        for(int i = answer; i < answer + K; i++)
        {
            Console.Write(arr[i] + " ");
        }
    }
}
 
// Driver Code
static public void Main()
{
     
    // Given array arr[]
    List arr = new List(){ 1, 2, 4, 5, 9,
                                     6, 4, 3, 7, 8 };
 
    int K = 4, X = 4;
 
    // Function call
    int answer = findSubarray(arr, K, X);
 
    // Function call to print subarray
    print(arr, answer, K);
}
}
 
// This code is contributed by akhilsaini


输出:
4 5 9 6


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