Java中BitSet的基本用法
- JAVA中BitSet就是“位图”数据结构,根据“位图”的语义,数据的存在性可以使用bit位上的1或0来表示;一个bit具有2个值:0和1,正好可以用来表示false和true
- 就是BitSet中一位就表示一个Bit位,空间消耗很小
int nextSetBit(int startIndex)
// 返回第一个设置为 true 的位的索引,在指定的起始索引或之后的索引上
int nextClearBit(int startIndex)
// 返回第一个设置为 false 的位的索引 , 在指定的起始索引或之后的索引上
void set(int startIndex, int endIndex, boolean v)
// 将指定索引处的位设置为指定的值[startIndex,endIndex)设置为v
// 无v默认true,无endIndex就是设置startIndex一个
BitSet.and(BitSet)
// 取两个BitSet的并集
public class Main {
public static void main(String[] args) {
BitSet set_1 = new BitSet();
set_1.set(3);// 将3设置为true
set_1.set(3, 5, true);
set_1.set(10, 15, true);
System.out.println(set_1);//{3, 4, 10, 11, 12, 13, 14}
System.out.println(set_1.size());// 返回bit位数量,为64的倍数,因为使用long类型维护的
System.out.println(set_1.get(4));// 判断是否存在
System.out.println(set_1.nextSetBit(0));//3
System.out.println(set_1.nextClearBit(3));//5
BitSet set_2 = new BitSet();
set_2.set(4, 8, true);
System.out.println(set_2);//{4, 5, 6, 7}
set_1.and(set_2);// 取位图并集
System.out.println(set_1);//{4}
System.out.println(set_2);// set_2无变化
}
}
例题56. 合并区间
class Solution {
public int[][] merge(int[][] intervals) {
BitSet bitSet = new BitSet();
int max = 0;
for (int[] interval : intervals) {
// 乘以2原因:若[3,4][5,6]进行应该4和5不会相连,但是BitSet中会存在{ 3, 4, 5, 6}
// 为避免这种情况*2就相当于给每一个相邻值之间插入了一个多余的值
int temp = interval[1] * 2 + 1;
bitSet.set(interval[0] * 2, temp, true);
max = Math.max(temp, max);
}
int index = 0, count = 0;
while (index < max) {
int start = bitSet.nextSetBit(index);
int end = bitSet.nextClearBit(start);
int[] item = {start / 2, (end - 1) / 2};
intervals[count++] = item
index = end;
}
int[][] ret = new int[count][2];
if (count >= 0) System.arraycopy(intervals, 0, ret, 0, count);
return ret;
}
}