英文:
why i am getting duplicates in my list after using containsKey method
问题
private static void makeList(int n, ArrayList<Integer> minimum, HashMap<Integer, Integer> ugly) {
for (int i = 1; minimum.size() < n; ++i) {
if (!ugly.containsKey(2 * i)) {
minimum.add(2 * i);
ugly.put(2 * i, 2 * i);
}
int m3 = 3 * i;
if (!ugly.containsKey(3 * i)) {
minimum.add(3 * i);
ugly.put(3 * i, 3 * i);
}
int m5 = 5 * i;
if (!ugly.containsKey(m5)) {
minimum.add(m5);
ugly.put(m5, m5);
}
}
}
英文:
i am using hashmap to validate that key dosent exist in the map and adding the key to a list i am using containsKey to prevent duplicate but its adding duplicate to my list
private static void makeList(int n,ArrayList<Integer> minimum ,HashMap<Integer,Integer> ugly) {
for(int i=1; minimum.size() < n; ++i) {
if(!ugly.containsKey(2*i)); {
minimum.add(2*i);
ugly.put(2*i,2*i );
}
int m3=3*i;
if(!ugly.containsKey(3*i)){
minimum.add(3*i);
ugly.put(3*i,3*i);
}
int m5=5*i;
if(!ugly.containsKey(m5)){
minimum.add(m5);
ugly.put(m5,m5);
}
}
}
答案1
得分: 2
我看到你在if()
条件后面加了分号;
。
只需将其删除然后尝试:
private static void makeList(int n, ArrayList<Integer> minimum, HashMap<Integer, Integer> ugly) {
for (int i = 1; minimum.size() < n; ++i) {
if (!ugly.containsKey(2 * i)) { // <-编辑部分,删除了分号
minimum.add(2 * i);
ugly.put(2 * i, 2 * i);
}
int m3 = 3 * i;
if (!ugly.containsKey(3 * i)) {
minimum.add(3 * i);
ugly.put(3 * i, 3 * i);
}
int m5 = 5 * i;
if (!ugly.containsKey(m5)) {
minimum.add(m5);
ugly.put(m5, m5);
}
}
}
英文:
I see you gave semicolon ;
after if()
condition
just remove that and try
private static void makeList(int n,ArrayList<Integer> minimum ,HashMap<Integer,Integer> ugly) {
for(int i=1; minimum.size() < n; ++i) {
if(!ugly.containsKey(2*i)) { //<-edited part, removed semicolon
minimum.add(2*i);
ugly.put(2*i,2*i );
}
int m3=3*i;
if(!ugly.containsKey(3*i)){
minimum.add(3*i);
ugly.put(3*i,3*i);
}
int m5=5*i;
if(!ugly.containsKey(m5)){
minimum.add(m5);
ugly.put(m5,m5);
}
}
答案2
得分: 0
简化并清晰代码。
private static void makeList(int n, List<Integer> minimum, Map<Integer, Integer> ugly) {
for (int i = 1; minimum.size() < n; i++)
for (int j : Arrays.asList(2, 3, 5))
if (ugly.put(i * j, i * j) == null)
minimum.add(i * j);
}
附注: 为什么你不使用 Set<Integer>
而不是带有 key == value
的 Map<Integer, Integer>
?
英文:
Be simple and it clear the code.
private static void makeList(int n, List<Integer> minimum, Map<Integer,Integer> ugly) {
for (int i = 1; minimum.size() < n; i++)
for (int j : Arrays.asList(2, 3, 5))
if(ugly.put(i * j, i * j) == null)
minimum.add(i * j);
}
P.S. Why don't you use Set<Integer>
instead of Map<Integer, Integer>
with key == value
?
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论