我就废话不多说了,直接上代码吧!
import datetime
def find_close(arr, e):
start_time = datetime.datetime.now()
size = len(arr)
idx = 0
val = abs(e - arr[idx])
for i in range(1, size):
val1 = abs(e - arr[i])
if val1 < val:
idx = i
val = val1
use_time = datetime.datetime.now() - start_time
return arr[idx], use_time.seconds * 1000 + use_time.microseconds / 1000
def find_close_fast(arr, e):
start_time = datetime.datetime.now()
low = 0
high = len(arr) - 1
idx = -1
while low <= high:
mid = int((low + high) / 2)
if e == arr[mid] or mid == low:
idx = mid
break
elif e > arr[mid]:
low = mid
elif e < arr[mid]:
high = mid
if idx + 1 < len(arr) and abs(e - arr[idx]) > abs(e - arr[idx + 1]):
idx += 1
use_time = datetime.datetime.now() - start_time
return arr[idx], use_time.seconds * 1000 + use_time.microseconds / 1000
if __name__ == "__main__":
arr = []
f = open("1Mints.txt")
for line in f:
arr.append(int(line))
f.close()
arr.sort()
while 1:
e = int(input("input a number:"))
print("find_close ", find_close(arr, e))
print ("find_close_fast ", find_close_fast(arr, e))
补充拓展:查询集合中最接近某个数的数
查询集合中最接近某个数的数
解题思路
一、采用C++ 中map容器,因为它可以实时对输入的元素进行排序。(map的使用可自行百度)
二、当集合为空时,输出“Empty!”;当集合中只有一个元素时,直接输出该元素。
三、下面重点看一般的情况。
1.先查找集合中是否有查询的元素,有则输出该元素
2.没有的话,将该元素先插入集合中,再查找该元素处于集合的某个位置。
若该元素在集合的首位,则输出该数的下一位。
若该元素在集合的末位,则输出该数的上一位。
否则,判断它左右元素的值与它的差的绝对值,输出差的绝对值较小的那个元素。若相等,则同时输出。
#include#include
以上这篇在python3中实现查找数组中最接近与某值的元素操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持考高分网。



