从包含关键点的地图中获取最接近关键点的最快方法:5、10、15、20、25,依此类推到200



我有几个键,可以是5、10、15等,最多200个,其中只包含5的倍数。每个键都有一个字符串连接,如本例所示:

5 = test5
10 = test10
15 = test15

我有一个变化的随机变量,可能在0-500之间。我想得到最接近的键及其字符串,我已经找到了一个解决方案,但我想知道是否有更好的解决方案,因为这种情况只使用5的倍数。

TreeMap<Long,String> map = new TreeMap<>();
map.put(5L,"a");
map.put(10L,"b");
map.put(25L,"e");
map.put(20L,"d");
map.put(15L,"c");
Long key = 42L;
Map.Entry<Long,String> low = map.floorEntry(key);
Map.Entry<Long,String> high = map.ceilingEntry(key);
Object res = null;
if (low != null && high != null) {
res = Math.abs(key-low.getKey()) < Math.abs(key-high.getKey())
?   low.getValue()
:   high.getValue();
} else if (low != null || high != null) {
res = low != null ? low.getValue() : high.getValue();
}
System.out.println(res);

您可以使用模数运算符来获取您正在查找的密钥

您可以使用类似的方法来计算最近的键,该键是5的倍数。

public Long getNearestKey(Long random) {
Long modulus = random % 5;
Long key = modulus < 3 ? random - modulus : random + (5 - modulus);
return key;
}

然后在方法中调用getNearestKey(42L),它将返回最接近的值。

一个简单的测试:

public static void main(String[] args) {
for(long i = 400; i <= 405; i++) 
System.out.println(getNearestKey(i));
}

public static Long getNearestKey(Long random) {
Long modulus = random % 5;
Long key = modulus < 3 ? random - modulus : random + (5 - modulus);
return key;
}

输出:

400
400 
400
405
405
405

您不需要排序的映射。只要做一些数学运算就可以了。

long key = ((key + 2) / 5) * 5

它的工作方式是这样的。

  1. 如果key的余数除以5时为0,1或2,则加2不会影响除以5。剩余部分将被丢弃,乘以5将得到最接近的较低倍数。

  2. 如果key除以5的余数是3或4,那么在进行相同的除法和乘法运算后,加2将把它推到下一个更高的倍数。

Map<Long, String> map = new HashMap<>();
map.put(5L, "a");
map.put(10L, "b");
map.put(25L, "e");
map.put(20L, "d");
map.put(15L, "c");
map.put(30L, "f");
map.put(0L, "g");
Random r = new Random();
for (int i = 0; i < 20; i++) {
long key = r.nextInt(31);
long save = key;
// simple calculation that guarantees nearest multiple of 5.
key = ((key + 2) / 5) * 5;
System.out.printf("Random = %3d,  key = %3d, value = %s%n", save,
key, map.get(key));
}

一个简单的方法可以是找到与给定随机数最接近的5的倍数,并检查该数是否存在于映射中(O(1((。如果存在,那将是答案如果不存在,最大值(200(或最小值(5(将是答案。

大于 200
小于5 的数字的最大值为200->

对于介于-
之间的数字,我们以和为例,取143,因此5的最接近倍数为145。这很容易找到。

相关内容

最新更新