从整数列表中,获取最接近给定值的数字 [英] From list of integers, get number closest to a given value

查看:26
本文介绍了从整数列表中,获取最接近给定值的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个整数列表,我想找到哪个数字最接近我在输入中给出的数字:

<预><代码>>>>myList = [4, 1, 88, 44, 3]>>>我的号码 = 5>>>takeClosest(myList, myNumber)...4

有没有什么快速的方法可以做到这一点?

解决方案

如果我们不确定列表是否已排序,我们可以使用 内置min()函数,找到离指定数字距离最小的元素.><预><代码>>>>min(myList, key=lambda x:abs(x-myNumber))4

请注意,它也适用于带有 int 键的字典,例如 {1: "a", 2: "b"}.这种方法需要 O(n) 时间.

<小时>

如果列表已经排序,或者您只能支付对数组排序一次的代价,请使用@中说明的二分法劳里茨的答案 只需要 O(log n) 时间(但请注意,检查列表是否已经排序是 O(n),排序是 O(n log n).)

Given a list of integers, I want to find which number is the closest to a number I give in input:

>>> myList = [4, 1, 88, 44, 3]
>>> myNumber = 5
>>> takeClosest(myList, myNumber)
...
4

Is there any quick way to do this?

解决方案

If we are not sure that the list is sorted, we could use the built-in min() function, to find the element which has the minimum distance from the specified number.

>>> min(myList, key=lambda x:abs(x-myNumber))
4

Note that it also works with dicts with int keys, like {1: "a", 2: "b"}. This method takes O(n) time.


If the list is already sorted, or you could pay the price of sorting the array once only, use the bisection method illustrated in @Lauritz's answer which only takes O(log n) time (note however checking if a list is already sorted is O(n) and sorting is O(n log n).)

这篇关于从整数列表中,获取最接近给定值的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆