用于查找列表中的数字(添加或减去时)是否等于模b

时间:2018-02-03 23:03:05

标签: algorithm

当我遇到一个我无法想到解决方案的有趣问题时,我正在做一些面试问题。问题表明:

  

设计一个接受整数数组的函数。最后两个数字       在这个数组中是'a'和'b'。该函数应该找到 all       当以某种方式求和/减去时,数组中的数字等于       a mod b,除了最后两个数字a和b。

所以,例如,让我们说我们有一个数组:

array = [5, 4, 3, 3, 1, 3, 5].

我需要查明此数组中是否存在+/-可能的“放置位置”,以使数字等于3 mod 5。该函数应为此数组打印True,因为5+4-3+3-1 = 8 = 3 mod 5

“明显”且简单的解决方案是尝试以所有可能的方式添加/减去所有内容,但这是一个非常复杂的时间复杂解决方案,也许 O(2 名词

有没有更好的方法呢?

编辑:问题要求函数在数组中使用所有数字,而不是任何。当然,除了最后两个。

3 个答案:

答案 0 :(得分:3)

如果有n个数,那么有一个简单的算法在O(b * n)中运行:对于k = 2到n,计算整数x的集合,使得前k个数的和或差是等于x modulo b。

对于k = 2,该集合包含(a_0 + a_1)模b和(a_0-a_1)模b。对于k = 3,4,...,n,您可以获取前一组中的数字,然后在数组中添加或减去下一个数字。最后检查a是否是最后一组的元素。

答案 1 :(得分:1)

java.sql.SQLException: defaultAuthenticationPlugin 'com.mysql.jdbc.authentication.MysqlNativePasswordPlugin' is not listed in "authenticationPlugins" nor it is one of the built-in plugins. 。我们举个例子,O(b * n)。让[5, 4, 3, 3, 1]表示m[i][j] mod 5到索引j是否存在解决方案:

i

但我们也可以减去

i = 0:
5 = 0 mod 5
m[0][0] = True

i = 1: 
0 + 4 = 4 mod 5
m[1][4] = True

检查以前的可能性:

0 - 4 = 1 mod 5
m[1][1] = True

i = 2:

我们实际上可以在那里停下来,但让我们采用与你的例子中不同的解决方案:

m[1][4] and m[1][1]

4 + 3 = 7 = 2 mod 5
4 - 3 = 1 = 1 mod 5
1 + 3 = 4 = 4 mod 5
1 - 3 = -2 = 3 mod 5

m[2][1] = True
m[2][2] = True
m[2][3] = True
m[2][4] = True

i = 3:

1 + 3 = 4 mod 5
1 - 3 = 3 mod 5
2 + 3 = 0 mod 5
2 - 3 = 4 mod 5
3 + 3 = 1 mod 5
3 - 3 = 0 mod 5
4 + 3 = 2 mod 5
4 - 3 = 1 mod 5

m[3][0] = True
m[3][1] = True
m[3][2] = True
m[3][3] = True
m[3][4] = True

i = 4: m[3][2] True means we had a solution for 2 at i=3 => 2 + 1 means m[4][3] = True + 1 + 3 + 3 - 4

答案 2 :(得分:0)

我根据提供的here数学解释编写了一个解决方案。我没有评论解决方案,所以如果你想要解释,我建议你阅读答案!

def kmodn(l):
    k, n = l[-2], l[-1]
    A = [0] * n
    count = -1
    domath(count, A, l[:-2], k, n)

def domath(count, A, l, k, n):
    if count == len(l):
        boolean = A[k] == 1
        print boolean
    elif count == -1:
        A[0] = 1; # because the empty set is possible
        count += 1
        domath(count, A, l, k, n)
    else:
        indices = [i for i, x in enumerate(A) if x == 1]
        b = [0] * n
        for i in indices:
            idx1 = (l[count] + i) % n
            idx2 = (i - l[count]) % n
            b[idx1], b[idx2] = 1, 1
        count += 1
        A = b
        domath(count, A, l, k, n)