使用Java的TreeMap来解决这个问题。TreeMap是基于红黑树实现的有序映射,可以按键进行排序。\n\n首先,将给定的key和value添加到TreeMap中:\n\njava\nMap<Integer, String> map = new TreeMap<>();\nmap.put(1, "1");\nmap.put(10, "10");\nmap.put(14, "14");\nmap.put(18, "18");\nmap.put(22, "22");\nmap.put(26, "26");\nmap.put(30, "30");\nmap.put(35, "35");\nmap.put(39, "39");\nmap.put(43, "43");\nmap.put(6, "6");\n\n\n然后,使用TreeMap的floorKey()方法查找小于等于给定数字的最大键值:\n\njava\nint target = 11;\nint nearestKey = ((TreeMap<Integer, String>) map).floorKey(target);\nString nearestValue = map.get(nearestKey);\n\nSystem.out.println("Nearest key: " + nearestKey);\nSystem.out.println("Nearest value: " + nearestValue);\n\n\n输出结果为:\n\n\nNearest key: 10\nNearest value: 10\n\n\n因此,小于11最近的数是10。

Java TreeMap 查找小于给定数字的最近键值

原文地址: https://www.cveoy.top/t/topic/qeoP 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录