[英]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)
For anyone confused on the Codility Sample Test对于任何对 Codility 样本测试感到困惑的人
Write a function:写一个 function:
def solution(A)定义解决方案(A)
that, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A.即,给定一个包含 N 个整数的数组 A,返回 A 中未出现的最小正 integer(大于 0)。
For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5.例如,给定 A = [1, 3, 6, 4, 1, 2],function 应该返回 5。
Given A = [1, 2, 3], the function should return 4.给定 A = [1, 2, 3],function 应该返回 4。
Given A = [−1, −3], the function should return 1.给定 A = [−1, −3],function 应返回 1。
Write an efficient algorithm for the following assumptions:为以下假设编写一个有效的算法:
N is an integer within the range [1..100,000]; N 是 [1..100,000] 范围内的 integer; each element of array A is an integer within the range [−1,000,000..1,000,000].
数组 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
I think the fastest solution is define an external vector "n" with all possible int from 1 to 100'000我认为最快的解决方案是定义一个外部向量“n”,所有可能的 int 从 1 到 100'000
N = np.arange(100_000)
def solution(A):
return n[~np.isin(N,A)][0]
I hope this is useful.我希望这很有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.