![](/img/trans.png)
[英]Python 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
[英]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.