5G的7位电话号码,去重,内存20mb,代码实现。

时间:2024-09-23 12:34:38

转自:http://www.aboutyun.com/thread-11139-1-1.html

答案:
首先,这个题考的不是分布式
7位数,至少要用int来保存,那么int为4字节,20MB内存 10^7*4/1024*1024=38.14697265625  至少需要38MB,显然7位的数字不能全部保存
保存一个数字不能用4字节,要用2字节或1字节,那么只能用short或byte,但是short最大65536,byte最大256,不能满足。
思路:
不管电话号码存在不存在,所有的电话号码一共有10^7个
建立一个byte类型的数组,数组大小为10^7,共需要10^7*1/1024*1024=9.5MB的内存 
数组的每个下标对应一个电话号码,数组的值代表是否重复,初始化的时候让数组里的每个值都为0,读到一次设为1,读到多次设2,那么值为1的就是去重后的号码。
代码:

public class SortTest {
public static void main(String[] args) {
int[] a = { 49, 38, 65, 97, 76, 13, 27, 49, 78, 34, 12, 64, 1,38,65 };
System.out.println("去重前...");
printSort(a);
byte[] ret = new byte[10000000];
for(int i=0;i<a.length;i++){
if (ret[a[i]] == 0)
ret[a[i]] = 1;
else if (ret[a[i]] == 1)
ret[a[i]] = 2;
}
System.out.println("去重后...");
for(int i=0;i<ret.length;i++){
if(ret[i]==1)
System.out.print(i + " ");
}
}
public static void printSort(int[] a){
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
System.out.println();
}
}