Python - K 之后最小的缺失元素
给定一个List,获取List中K之后的最小缺失元素。
Input : test_list = [1, 3, 4, 5, 7, 9, 10], K = 5
Output : 6
Explanation : After 5, 6 is 1st element missing in list.
Input : test_list = [1, 3, 4, 5, 7, 9, 11], K = 9
Output : 10
Explanation : After 9, 10 is 1st element missing in list.
方法:使用循环
在这里,我们遍历数字并使用条件检查列表中是否存在大于 K 的元素。
Python3
# Python3 code to demonstrate working of
# Smallest missing element after K
# Using loop
# initializing list
test_list = [1, 3, 4, 5, 7, 9, 10]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 7
ele = 1
# infinite loop to break at element found
while(1):
# checking if greater than K and not in list
if ele > K and ele not in test_list:
res = ele
break
ele = ele + 1
# printing result
print("The Smallest element greater than K in list : " + str(res))
输出
The original list is : [1, 3, 4, 5, 7, 9, 10]
The Smallest element greater than K in list : 8