简体   繁体   English

使用 BitSet 从 Array 中删除重复项?

[英]Remove duplicates from Array using BitSet?

I'm trying to understand the implementation of below statement found on stackoverflow我正在尝试了解在 stackoverflow 上找到的以下语句的实现

Can use BitSet, as you walk the array of values, set the corresponding bit to true.可以使用BitSet,当你遍历数组值时,将相应的位设置为true。 Then you can walk over the bit set and output the corresponding value whenever you find a bit set to true然后你可以遍历位设置和 output 对应的值,只要你发现一个位设置为真

I know very simple way of removing duplicates from array of int .我知道从int array中删除重复项的非常简单的方法。 But struggling to understand how it can be implemented using above statement found on this site.但是很难理解如何使用本网站上的上述声明来实现它。

ref link参考链接

https://stackoverflow.com/questions/3667543/remove-duplicates-from-a-large-integer-array-using-java

can anyone suggest how it can be implemented?谁能建议如何实施?

You can do it like so:你可以这样做:

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);
  }
}

As noted by ewramner , BitSet is not sparse, so this will allocate enough bits for everything up to the largest value in the array.正如ewramner所指出的, BitSet不是稀疏的,因此这将为数组中最大值的所有内容分配足够的位。 If there are very few values in the array, or they are all a lot larger than zero, this will probably be quite inefficient, and putting things in a Set (eg a HashSet or TreeSet ) would be a better option.如果数组中的值很少,或者它们都比零大很多,这可能会非常低效,将事物放入Set (例如HashSetTreeSet )将是更好的选择。


This is a more efficient way to walk over the bitset looking for true values:这是一种更有效地遍历 bitset 以查找真值的方法:

for (int i = -1; (i = bs.nextSetBit(i + 1)) != -1;) {
  System.out.println(i);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM