如何打印连续删除奇数索引后的最后一个元素



我正在尝试删除从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错误,这个逻辑出了什么问题?

有人能修好吗?

感谢和问候;

也许HashMap不是在这里使用的正确类。无论如何,正如@Welbog所指出的,你永远不会从你的桌子上拿走任何东西。另外,为什么要使用递归?

试试这样的东西:

while (hm.size() > 1) {
int j = 1;
int last = hm.size();
for (int i = 1; i <= last; i++) {
int value = hm.remove(i);
if (i % 2 == 0) {
hm.put(j, value);
j++;
}
}
}

有三种可能的解决方案。

(1( 我不知道你为什么需要申请";去除过程";在具有该逻辑的HashMap上,无论如何,一个可能的解决方案可以是以下解决方案。但是,只有当您需要应用到Map时才使用它,因为某些原因,您需要通过在Map键上应用该逻辑来删除它的条目。

public class RemovingOddIndexes {
public static void main(String[] args) {
// initialize
int n = 6;
HashMap<Integer, Integer> hm = new HashMap<>();
for (int i = 1; i <= n; i++) {
hm.put(i, i);
}
//
oddDeletions(hm);
// print result
hm.forEach((k, v) -> System.out.println(String.format("%s:%s, ", k, v)));
}
public static void oddDeletions(HashMap<Integer, Integer> hm) {
while (hm.size() > 1) {
hm.keySet()
.stream()
.sorted()
.forEach(new Consumer<Integer>() {
int i = 1;
@Override
public void accept(Integer n) {
if (i % 2 == 1)
hm.remove(n);
++i;
}
});
}
}
}

(2( 否则,使用一个简单的LinkedList,您可以递归地浏览它。我更喜欢使用LinkedList而不是ArrayList,因为alg需要在每次迭代中删除元素,直到最后一次。并且在LinkedList上的移除操作执行得更好。

public class RemovingOddIndexes {
public static void main(String[] args) {
// initialize
int n = 6;
List<Integer> list = new LinkedList<>();
for (int i = 1; i <= n; i++) {
list.add(i);
}
//
oddDeletions(list);
// print result
list.forEach(i -> System.out.println(String.format("%s, ", i)));
}
public static void oddDeletions(List<Integer> list) {
while (list.size() > 1) {
int i = 1;
Iterator<Integer> it = list.iterator();
while (it.hasNext()) {
it.next();
if (i++ % 2 == 1) {
it.remove();
}
}
}
}
}

(3( 最后一个选项,最快的方式

int lastOdd = 1 << (int)(Math.log(n) / Math.log(2))

最新更新