1
我非常新的列表,隊列等如何使用key ++將x-1和x + 1添加到HashMap?
我想帶內的關鍵我每一個值,加/減1到每一個,給他們鑰匙我+ 1,然後取每個值從i + 1等等。 比如我想,如果我輸入
3
地圖上看起來像地圖K,V
0, 3
1, 4
1, 2
2, 5
2, 3
2, 3
2, 1 -- Now it will end, because !map.containsValue(1) == false
這是代碼,我有
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
Integer x = sc.nextInt();
Integer i = 1;
map.put(0, x);
while (!map.containsValue(1)) {
for (Map.Entry<Integer, Integer> a : map.entrySet()) {
if (a.getKey().equals(i)) {
map.put(i++, (x-1));
map.put(i++, (x+1));
}
i++;
}
}
我不是固定的使用HashMap,如果有更好的解決方案(使用鍵找到一個值,而不是索引),請打我!感謝您的回答。
你想,也許使用二維數組一樣'陣列[關鍵] [ MAX] = value',並刪除所有'array [key] [MAX] .equals(0)'會更好? – OhOkay