如何找到包含最小值的数组



我有一个数字子数组的数组,我想找到包含最小数字的子数组。

data = [
[10, 11],
[93, 3], # This is the required sub-array because 3 is smaller than all the other numbers
[33, 44, 55]
]
# tag the smallest item from each sub-array onto the front, creating a new main array
extendedData = map(lambda x:(min(x), x),data)
# use the fact that when given an array, min() will examine the first element
(smallestValueFromRow, rowContainingSmallestValue) = min(extendedData)
print(rowContainingSmallestValue)

下面是一个工作示例:https://www.online-python.com/7O5SceGoEF

有没有一种更有效的方法来解决这个问题?在实践中,数组和子数组可能相当大,我假设map函数会复制data数组,并应用映射。

您的第一个解决方案,使用map,应该不需要超过常量的额外空间,因为map返回生成器——在您迭代它之前,它实际上不会做任何事情

然而,你可以用更少的打字有效地完成同样的事情:

print(min(data, key=min))

这里有一个解决方案,它将返回包含最小值的第一个列表:

data = [
[10, 11],
[93, 3], 
[33, 44, 55]
]    
smallestNumbersFromEachSubList = [min(subList) for subList in data]
subListContainingTheSmallestNumber = data[smallestNumbersFromEachSubList.index(min(smallestNumbersFromEachSubList))]
print(subListContainingTheSmallestNumber)

这将返回:

[93, 3]

由于您要求内存高效的实现,这种方法将是恒定空间

min_num = min_idx = float("inf")
for i, nums in enumerate(data):
local_min = min(nums)
if local_min < min_num:
min_idx = i
min_num = min(min_num, local_min)
print(data[min_idx])

最新更新