繁体   English   中英

给定一个包含 N 个整数的数组 A,返回在 O(n) 时间复杂度内不会出现在 A 中的最小正 integer(大于 0)(Python Sol)

[英]Given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A in O(n) time complexity (Python Sol)

对于任何对 Codility 样本测试感到困惑的人

写一个 function:

定义解决方案(A)

即,给定一个包含 N 个整数的数组 A,返回 A 中未出现的最小正 integer(大于 0)。

例如,给定 A = [1, 3, 6, 4, 1, 2],function 应该返回 5。

给定 A = [1, 2, 3],function 应该返回 4。

给定 A = [−1, −3],function 应返回 1。

为以下假设编写一个有效的算法:

N 是 [1..100,000] 范围内的 integer; 数组 A 的每个元素都是 [−1,000,000..1,000,000] 范围内的 integer。

# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")

def solution(A):
    # write your code in Python 3.6
    pass

    #check that if maximum number in array is less than 1 then the smallest positive integer that doesn't occur in A will be 1
    if max(A) < 1:
        return 1
    
    #sorted set of A
    hashset = set(A)

    #smallest possible positive integer
    result = 1

    #iterate through array seeing if the integer is in the hashset
    while result in hashset:
        
        #increment result
        result += 1
    
    #return smallest positive integer (greater than 0) that does not occur in A
    return result

我认为最快的解决方案是定义一个外部向量“n”,所有可能的 int 从 1 到 100'000

N = np.arange(100_000)
def solution(A):
    return n[~np.isin(N,A)][0]

我希望这很有用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM