python - 确定给定数组的任何排列是否使长度为 K 的所有子数组的总和相等

标签 python arrays algorithm

我在一次采访中被问到这个问题。

You are given an array consisting of N integers. You need to determine whether any permutation of a given array exists such that the sum of all subarrays of length K are equal. N is divisible by K i.e. N mod K = 0.
If the array is [1,2,1,3,2,3] and K = 2, it is False.
If the array is [1,2,1,3,2,3] and K = 3, it is True.

我的逻辑是这样的。

1) If N == K, return True.
2) Else store each of the distinct element in the array in a dictionary. If the number of distinct elements in the dictionary is greater than K, return False.
3) Else store the count of each distinct element in the dictionary.
4) If the count of any distinct element is less than (N/K), return False.
5) Finally return True.

这是我的 Python 代码:

def check(nums, n, k):
if n == k:
    return True
else:
    my_dict = {}
    for i in nums:
        if i not in my_dict:
            my_dict[i] = 1
        else:
            my_dict[i] += 1
    if len(my_dict) > k:
        return False
    count = int(n/k)
    for i,j in my_dict.items():
        if j < count:
            return False
    return True  

我的做法是否正确?有更好的方法吗?

最佳答案

您的解决方案几乎是正确的。问题是,元素计数需要被 n / k 整除。 .

证明

假设我们得到了一个满足条件的排列。对于任何不同的元素,很容易观察到,如果在 i 的排列中找到它, 也必须在以下位置找到它:i - k, i - 2k,... ,i mod ki + k, i + 2k,.., n - k + (i mod k) ,因此出现在 i暗示暗示出现在i % k < k .现在,在索引低于 k 的位置出现每个不同的事件暗示n / k总次数(这里 n mod k = 0 很重要)。

OP 解决方案的反例

一个会破坏你解决方案的例子(几乎肯定是最小的):

n = 8, k = 4 array = [1, 1, 1, 2, 2, 2, 2, 2]

关于python - 确定给定数组的任何排列是否使长度为 K 的所有子数组的总和相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52244225/

相关文章:

c++ - 如何在 std::array<> 上使用 std::for_each 并在每个元素上应用 lambda 函数?

algorithm - 如何确定一个点的旋转角度

python - 从 scipy interpolate/griddata 检索数据点

.net - .NET 数组的最大大小

python - 如何在没有 2 个 for 循环的情况下迭代矩阵

arrays - 无法让 Powershell 提取 $StrComputer.name

algorithm - 自主解迷宫机器人与故障路径排序

algorithm - 拓扑排序算法

python - 按变量分组、排序和打印来自另一列的值

python - 模拟补丁一个类上不存在的函数