日期:2014-05-20  浏览次数:20692 次

在一个有40000个32位整数的顺序文件中,找出一个至少出现了2次的数,请问各位是怎么想的?
如题:
  在一个有40000个32位整数的顺序文件中,找出一个至少出现了2次的数,请问各位是怎么想的?

------解决方案--------------------
要想简单就用HashSet
要想复杂就自己写个Set
------解决方案--------------------
就是遍历这4000个数,然后分类,将数保存到set中就可以,每次检查新数时都判断集合里有没有,如果没有就放进去,有的话,那么这个数就是首先出现两次的
------解决方案--------------------
楼上两位的办法,无非就是“每读出一个数,就跟前面所有的数相比较”,如果这样的化,还是不要用 Set 了,干脆自己搞个数组,然后逐个判断好了,能省点内存,速度也许还能快点。
------解决方案--------------------
package practice;

public class Test {
public static void main(String args[]) {
Test test = new Test();
int nums[] = new int[] { 1, 1, 3, 3, 4, 4, 4, 5 };
test.getMoreThanTwo(nums);
}

public void getMoreThanTwo(int nums[]) {
int hash[] = new int[40000];
for (int i = 0; i < hash.length; i++) {
hash[i] = 0;
}
for (int i = 0; i < nums.length; i++) {
hash[nums[i]]++;
}
for (int i = 0; i < hash.length; i++) {
if (hash[i] > 0)
System.out.println( "the number " + i + " show " + hash[i]
+ " times. ");
}
}
}
输出的结果
the number 1 show 2 times.
the number 3 show 2 times.
the number 4 show 3 times.
the number 5 show 1 times.

------解决方案--------------------
在一个有40000个32位整数的“顺序”文件中

“顺序”的意思是排序过了吗?如果已经排序过了,那么读取的时候只要找到连续两个相同的数字就是答案了
------解决方案--------------------
“32 位整数”,那就不能使用 int 了。
------解决方案--------------------
chen_jian() 的方法有问题:
int nums[] = new int[] { 1, 1, 3, 3, 4, 4, 4, 5 };
如果nums元素大小超过40000,hash表就越界了。