【发布时间】:2021-05-07 12:54:55
【问题描述】:
我正在尝试从 1 开始连续删除奇数位置并获取最后一个剩余元素;
例如:
n=6;
1 2 3 4 5 6
首先:删除奇数索引将得到 (2 4 6);
第二个:删除奇数索引将得到 (4),这就是答案...
这是我的代码:
import java.util.HashMap;
public class Odd_Deletions {
public static void oddDeletions(HashMap<Integer, Integer> hm) {
int j = 1;
for (int i = 1; i < hm.size(); i++) {
if (hm.get(i) % 2 != 0) {
continue;
} else {
hm.put(j, i);
j++;
}
}
//System.out.println(hm);
while (true) {
if (hm.size() == 1) {
System.out.println(hm);
break;
} else
oddDeletions(hm);
}
}
public static void main(String args[]) {
int n = 6;
HashMap<Integer, Integer> hm = new HashMap<>();
for (int i = 1; i <= n; i++) {
hm.put(i, i);
}
//System.out.println(hm);
oddDeletions(hm);
}
}
为什么我收到 StackOverflow 错误,这个逻辑有什么问题?
谁能解决?
感谢和问候;
【问题讨论】:
-
试运行
oddDeletions方法。你有一个递归,但它什么时候停止? -
你永远不会从
hm中删除任何东西。 -
也许
HashMap不是在这里使用的正确类 -
对于某个正整数 n,答案将始终是
2^n形式的最大索引,因此如果您知道输入的大小,则可以在恒定时间内计算答案。
标签: java data-structures hashmap