我正在撰寫一種方法來洗掉整數 ArrayList 中相鄰的重復值。
public static void remove2InARow(ArrayList<Integer> list) {
for (int i = 0; i < list.size() - 1; i ) {
if (list.get(i) == list.get(i 1)) {
list.remove(i);
}
}
}
如果您[3,4,3,3]作為引數傳入,則輸出將為[3,4,3].
當相同的值重復超過 2 次時,此實作會出現問題。例如,當它應該是時[1, 2, 5, 4, 6, 6, 6, 1, 2]變為。同樣,應該成為。[1, 2, 5, 4, 6, 6, 1, 2][1, 2, 5, 4, 6, 1, 2][n, ..., n][n]
有沒有辦法使我的實作適應遞回?它甚至需要遞回嗎?
uj5u.com熱心網友回復:
它當然不需要遞回!
問題的根源是在迭代集合時從集合中洗掉元素可能會導致一些意外行為,在迭代串列時盡量不要觸摸串列,然后一旦完成 - 洗掉你需要的元素。
uj5u.com熱心網友回復:
import java.util.stream.Collectors;
public static void remove2InARow(ArrayList<Integer> list) {;
list= list.stream().distinct().collect(Collectors.toList());
System.out.println(list);
}
也許它會幫助你!
uj5u.com熱心網友回復:
public static void remove2InARow(ArrayList<Integer> list) {
for (int i = 0; i < list.size() - 1; i ) {
if (list.get(i) == list.get(i 1)) {
list.remove(i);
i--;
}
}
}
這對我有用。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/513471.html
標籤:爪哇递归数组列表
下一篇:遍歷嵌套的Python字典?
