📌  相关文章
📜  检查是否存在大小为K的子数组,其元素形成一个可被3整除的数字

📅  最后修改于: 2021-05-17 21:41:04             🧑  作者: Mango

给定大小为N的数组arr []和正整数K ,任务是找到大小为K的子数组,其元素可用于生成可被3整除的数字。如果不存在这样的子数组,则打印– 1

例子:

天真的方法:最简单的方法是从给定的数组生成大小为K的所有可能的子数组,对于每个子数组,检查该子数组形成的数字是否可被3整除。

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

高效方法:为了优化上述方法,该想法基于以下观察:

请按照以下步骤解决问题:

  1. 将数组的前K个元素的总和存储在一个变量中,例如sum
  2. 遍历数组的其余元素
  3. 使用滑动窗口技术,从总和中减去子数组的第一个元素,然后将下一个数组元素添加到子数组中。
  4. 在每个步骤中,检查总和是否可被3整除。
  5. 如果发现为真,则打印当前的K大小子数组。
  6. 如果找不到这样的子数组,则打印-1。

下面是上述方法的实现。

C++
// C++ implementation of the above approach
#include 
using namespace std;
 
// Function to find the
// K size subarray
void findSubArray(vector arr, int k)
{
    pair ans;
    int i, sum = 0;
 
    // Check if the first K elements
    // forms a number which is
    // divisible by 3
    for (i = 0; i < k; i++) {
        sum += arr[i];
    }
 
    int found = 0;
    if (sum % 3 == 0) {
        ans = make_pair(0, i - 1);
        found = 1;
    }
 
    // Using Sliding window technique
    for (int j = i; j < arr.size(); j++) {
 
        if (found == 1)
            break;
 
        // Calculate sum of next K
        // size subarray
        sum = sum + arr[j] - arr[j - k];
 
        // Check if sum is divisible by 3
        if (sum % 3 == 0) {
 
            // Update the indices of
            // the subarray
            ans = make_pair(j - k + 1, j);
            found = 1;
        }
    }
 
    // If no such subarray is found
    if (found == 0)
        ans = make_pair(-1, 0);
 
    if (ans.first == -1) {
        cout << -1;
    }
    else {
        // Print the subarray
        for (i = ans.first; i <= ans.second;
             i++) {
            cout << arr[i] << " ";
        }
    }
}
 
// Driver's code
int main()
{
    // Given array and K
    vector arr = { 84, 23, 45,
                        12, 56, 82 };
    int K = 3;
 
    // Function Call
    findSubArray(arr, K);
 
    return 0;
}


Java
// Java implementation of the above approach
import java.util.*;
import java.awt.Point;
 
class GFG{
     
// Function to find the
// K size subarray
public static void findSubArray(Vector arr,
                                int k)
{
    Point ans = new Point(0, 0);
    int i, sum = 0;
   
    // Check if the first K elements
    // forms a number which is
    // divisible by 3
    for(i = 0; i < k; i++)
    {
        sum += arr.get(i);
    }
   
    int found = 0;
    if (sum % 3 == 0)
    {
        ans = new Point(0, i - 1);
        found = 1;
    }
   
    // Using Sliding window technique
    for(int j = i; j < arr.size(); j++)
    {
        if (found == 1)
            break;
   
        // Calculate sum of next K
        // size subarray
        sum = sum + arr.get(j) - arr.get(j - k);
   
        // Check if sum is divisible by 3
        if (sum % 3 == 0)
        {
             
            // Update the indices of
            // the subarray
            ans = new Point(j - k + 1, j);
            found = 1;
        }
    }
   
    // If no such subarray is found
    if (found == 0)
        ans = new Point(-1, 0);
   
    if (ans.x == -1)
    {
        System.out.print(-1);
    }
    else
    {
         
        // Print the subarray
        for(i = ans.x; i <= ans.y; i++)
        {
            System.out.print(arr.get(i) + " ");
        }
    }
}
 
// Driver code
public static void main(String[] args)
{
     
    // Given array and K
    Vector arr = new Vector();
    arr.add(84);
    arr.add(23);
    arr.add(45);
    arr.add(12);
    arr.add(56);
    arr.add(82);
     
    int K = 3;
   
    // Function call
    findSubArray(arr, K);
}
}
 
// This code is contributed by divyeshrabadiya07


Python3
# Python3 implementation of the
# above approach
 
# Function to find the
# K size subarray
def findSubArray(arr, k):
     
    ans = [(0, 0)]
    sm = 0
    i = 0
     
    found = 0
     
    # Check if the first K elements
    # forms a number which is
    # divisible by 3
    while (i < k):
        sm += arr[i]
        i += 1
 
    if (sm % 3 == 0):
        ans = [(0, i - 1)]
        found = 1
 
    # Using Sliding window technique
    for j in range(i, len(arr), 1):
        if (found == 1):
            break
 
        # Calculate sm of next K
        # size subarray
        sm = sm + arr[j] - arr[j - k]
 
        # Check if sm is divisible by 3
        if (sm % 3 == 0):
             
            # Update the indices of
            # the subarray
            ans = [(j - k + 1, j)]
            found = 1
 
    # If no such subarray is found
    if (found == 0):
        ans = [(-1, 0)]
 
    if (ans[0][0] == -1):
        print(-1)
    else:
         
        # Print the subarray
        for i in range(ans[0][0], 
                       ans[0][1] + 1, 1):
            print(arr[i], end = " ")
 
# Driver code
if __name__ == '__main__':
     
    # Given array and K
    arr = [ 84, 23, 45, 12, 56, 82 ]
    K = 3
 
    # Function call
    findSubArray(arr, K)
 
# This code is contributed by SURENDRA_GANGWAR


C#
// C# implementation of
// the above approach
using System;
using System.Collections.Generic;
class GFG{
 
class Point
{
  public int x, y;
  public Point(int first,
               int second) 
  {
    this.x = first;
    this.y = second;
  }   
}
 
// Function to find the
// K size subarray
public static void findSubArray(List arr,
                                int k)
{
  Point ans = new Point(0, 0);
  int i, sum = 0;
 
  // Check if the first K elements
  // forms a number which is
  // divisible by 3
  for(i = 0; i < k; i++)
  {
    sum += arr[i];
  }
 
  int found = 0;
  if (sum % 3 == 0)
  {
    ans = new Point(0, i - 1);
    found = 1;
  }
 
  // Using Sliding window technique
  for(int j = i; j < arr.Count; j++)
  {
    if (found == 1)
      break;
 
    // Calculate sum of next K
    // size subarray
    sum = sum + arr[j] -
          arr[j - k];
 
    // Check if sum is
    // divisible by 3
    if (sum % 3 == 0)
    {
      // Update the indices of
      // the subarray
      ans = new Point(j - k + 1, j);
      found = 1;
    }
  }
 
  // If no such subarray is found
  if (found == 0)
    ans = new Point(-1, 0);
 
  if (ans.x == -1)
  {
    Console.Write(-1);
  }
  else
  {
    // Print the subarray
    for(i = ans.x; i <= ans.y; i++)
    {
      Console.Write(arr[i] + " ");
    }
  }
}
 
// Driver code
public static void Main(String[] args)
{
  // Given array and K
  List arr = new List();
  arr.Add(84);
  arr.Add(23);
  arr.Add(45);
  arr.Add(12);
  arr.Add(56);
  arr.Add(82);
 
  int K = 3;
 
  // Function call
  findSubArray(arr, K);
}
}
 
// This code is contributed by Rajput-Ji


输出:
12 56 82









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