给定一个由N 个元素组成的arr[] ,任务是计算大小为K 的所有子数组,这些子数组至少有一对,其绝对差可被K – 1整除。
例子:
Input: arr[] = {1, 5, 3, 2, 17, 18}, K = 4
Output: 3
Explanation:
The three subarrays of size 4 are:
{1, 5, 3, 2}: Pair {5, 2} have difference divisible by 3
{5, 3, 2, 17}: Pairs {5, 2}, {5, 17}, {2, 17} have difference divisible by 3
{3, 2, 17, 18}: Pairs {3, 18}, {2, 17} have difference divisible by 3
Input: arr[] = {1, 2, 3, 4, 5}, K = 5
Output: 1
Explanation:
{1, 2, 3, 4, 5}: Pair {1, 5} is divisble by 4
天真的方法:
解决该问题的最简单方法是迭代所有大小为K 的子数组,并检查是否存在差值可被K – 1整除的任何对。
时间复杂度: O(N * K * K)
高效方法:上述方法可以使用鸽巢原理进行优化。请按照以下步骤解决问题:
- 考虑分别标记为0, 1, 2, …, K-2 的K-1框。它们表示当数组中的任何数字 x 除以K-1时的余数,这意味着框存储数组元素的模 K-1 。
- 现在,在大小为K的子数组中,根据鸽巢原理,必须至少有一对余数相同的盒子。这意味着至少有一对其差甚至总和可以被K整除。
- 从这个定理我们可以得出结论,每个大小为K 的子数组总是至少有一对,其差可以被K-1整除。
- 因此,答案将等于给定数组中可能的大小为K的子数组的数量,即N – K + 1 。
下面是上述方法的实现:
C++
// C++ implementation of the
// above approach
#include
using namespace std;
// Function to return the required
// number of subarrays
int findSubarrays(int arr[],
int N,
int K)
{
// Return number of possible
// subarrays of length K
return N - K + 1;
}
// Driver Code
int main()
{
int arr[] = { 1, 5, 3, 2, 17, 18 };
int K = 4;
int N = sizeof(arr) / sizeof(arr[0]);
cout << findSubarrays(arr, N, K);
return 0;
}
Java
// Java implementation of the
// above approach
class GFG{
// Function to return the required
// number of subarrays
static int findSubarrays(int arr[], int N,
int K)
{
// Return number of possible
// subarrays of length K
return N - K + 1;
}
// Driver Code
public static void main(String[] args)
{
int arr[] = { 1, 5, 3, 2, 17, 18 };
int K = 4;
int N = arr.length;
System.out.print(findSubarrays(arr, N, K));
}
}
// This code is contributed by shivanisinghss2110
Python3
# Python3 implementation of the
# above approach
# Function to return the required
# number of subarrays
def findSubarrays(arr, N, K):
# Return number of possible
# subarrays of length K
return N - K + 1;
# Driver Code
if __name__ == '__main__':
arr = [ 1, 5, 3, 2, 17, 18 ];
K = 4;
N = len(arr);
print(findSubarrays(arr, N, K));
# This code is contributed by Rohit_ranjan
C#
// C# implementation of the
// above approach
using System;
class GFG{
// Function to return the required
// number of subarrays
static int findSubarrays(int []arr, int N,
int K)
{
// Return number of possible
// subarrays of length K
return N - K + 1;
}
// Driver Code
public static void Main(String[] args)
{
int []arr = { 1, 5, 3, 2, 17, 18 };
int K = 4;
int N = arr.Length;
Console.Write(findSubarrays(arr, N, K));
}
}
// This code is contributed by Amit Katiyar
Javascript
3
时间复杂度: O(1)
辅助空间: O(1)
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live