[英]Remove duplicates from Array using BitSet?
我正在嘗試了解在 stackoverflow 上找到的以下語句的實現
可以使用BitSet,當你遍歷數組值時,將相應的位設置為true。 然后你可以遍歷位設置和 output 對應的值,只要你發現一個位設置為真
我知道從int
array
中刪除重復項的非常簡單的方法。 但是很難理解如何使用本網站上的上述聲明來實現它。
參考鏈接
https://stackoverflow.com/questions/3667543/remove-duplicates-from-a-large-integer-array-using-java
誰能建議如何實施?
你可以這樣做:
BitSet bs = new BitSet();
// walk the array of values
for (int i : array) {
// set the corresponding bit to true
bs.set(i);
}
// walk over the bit set
for (int i = 0; i < bs.size(); ++i) {
// output the corresponding value whenever you find a bit set to true
if (bs.get(i)) {
System.out.println(i);
}
}
正如ewramner所指出的, BitSet
不是稀疏的,因此這將為數組中最大值的所有內容分配足夠的位。 如果數組中的值很少,或者它們都比零大很多,這可能會非常低效,將事物放入Set
(例如HashSet
或TreeSet
)將是更好的選擇。
這是一種更有效地遍歷 bitset 以查找真值的方法:
for (int i = -1; (i = bs.nextSetBit(i + 1)) != -1;) {
System.out.println(i);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.