3 回答

TA貢獻1963條經驗 獲得超6個贊
您不需要排序的地圖。只要用一些數學來做就可以了。
long key = ((key + 2) / 5) * 5
它的工作方式是這樣的。
如果除以 5 的余數
key
為 0、1 或 2,則加 2 不會影響除以 5。余數將被舍去,乘以 5 將得到最接近的較小倍數。如果
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));
}

TA貢獻1936條經驗 獲得超7個贊
您可以使用模運算符來獲取您要查找的密鑰
您可以使用類似的方法來計算最近的 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

TA貢獻1863條經驗 獲得超2個贊
一種簡單的方法是找到最接近給定隨機數的 5 倍數,并檢查該數字是否存在于地圖中 ( O(1))。如果存在,則為答案,如果不存在,則答案為最大值 (200) 或最小值 (5)。
最大 200 -> 對于大于200 的數字
最小 5 -> 對于小于5的數字
對于介于兩者之間的數字 -
以 143 為例,因此最接近的 5 的倍數將是 145。這很容易找到。
添加回答
舉報