【发布时间】:2015-03-12 12:21:10
【问题描述】:
我在破解编码面试书时遇到了这个问题。
问题:给定一个包含 40 亿个非负整数的输入文件, 提供一种算法来生成一个不包含在 文件。假设您有 1 GB 的内存可用于此任务。
我的问题:为什么我们不能使用 BitSet 而不是 Byte[] ?这不会简化事情吗?
代码:
long numberOflnts = ((long) Integer.MAX_VALUE) + I;
byte[] bitfield = new byte [(int) (numberOflnts / 8)];
void findOpenNumberQ throws FileNotFoundException {
Scanner in = new Scanner(new FileReader("file.txt"));
while (in.hasNextlntQ) {
int n = in.nextlnt ();
/* Finds the corresponding number in the bitfield by using
* the OR operator to set the nth bit of a byte
* (e.g., 10 would correspond to the 2nd bit of index 2 in
* the byte array). */
bitfield [n / 8] |= 1 « (n % 8);
}
for (int i = 0; i < bitfield.length; i++) {
for (int j = 0; j < 8; j++) {
/* Retrieves the individual bits of each byte. When 0 bit
* is found, finds the corresponding value. */
if ((bitfield[i] & (1 « j)) == 0) {
System.out.println (i * 8 + j);
return;
}
}
}
}
跟进: 如果您只有 10 MB 的内存怎么办?假设所有值都是不同的。
【问题讨论】:
-
这不是“编程珍珠”的问题吗?
-
为什么我们不能使用 BitSet 而不是 Byte[] ?
-
@Walt
BitSet是特定于 Java 的。问题不是。你也错过了问题的重点。 -
哦,好的。所以,我认为我们可以很好地使用BitSet。我现在该怎么处理这个问题?删除它?
标签: java algorithm bitset large-data