答复: 一道腾讯面试题:从大量数字中取出 top 100

从1亿个数字中取出最大的100个
JVM需要调到-Xmx1024M,以免溢出


public class findValue {

public static void main(String[] args){

int max = 10000*10000;
int length=100;
int ints[] = new int[max];
Random random = new Random();
for (int i=0;i ints[i]=Math.abs(random.nextInt(max));
}
List list = new ArrayList();

long start = System.currentTimeMillis();
int size=0;
int value=0;
list.add(ints[0]);
for(int i=1;i value=ints[i];
size=list.size();
if(value if(size list.add(value);
}
continue;
}else if(value>list.get(0)){
list.add(0,value);
if(size==length){
list.remove(size);
}
continue;
}

for(int j=0;j if(value>list.get(j)){
//如果不需要排除重复数字,则去掉该判断
if(j>0&&value!=list.get(j-1)){
list.add(j,value);
if(size==length){
list.remove(size);
}
}
break;
}
}
}

System.out.println("time:"+(System.currentTimeMillis()-start));

System.out.println(list);
TreeSet set = new TreeSet();
set.addAll(list);

System.out.println(set.size()+":"+list.size());
if(set.size()!=list.size()){
System.out.println("error");
}
int i=0;
for(Iterator it=set.iterator();it.hasNext();){
value=it.next();
System.out.println(value+":"+list.get(list.size()-1-i));
if(value!=list.get(list.size()-1-i)){
System.out.println("error");
break;
}
i++;
}
}
}


E2160 3G
time:2453

你可能感兴趣的:(答复: 一道腾讯面试题:从大量数字中取出 top 100)