首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

1亿条数据中获取最大100条,论坛找来的代码TreeSet 跟另外一种方法

2012-08-26 
1亿条数据中获取最大100条,论坛找来的代码TreeSet 和另外一种方法import java.util.ArrayListimport java

1亿条数据中获取最大100条,论坛找来的代码TreeSet 和另外一种方法

import java.util.ArrayList;import java.util.Iterator;import java.util.List;import java.util.Random; import java.util.Set; import java.util.TreeSet; class TreeSF {public static Set<Integer> getTop100(int[] inputArray) {TreeSet<Integer> top100 = new TreeSet();for (int i = 0; i < inputArray.length; i++) {if (top100.size() < 100) {top100.add(inputArray[i]);} else if ((Integer) top100.first() < inputArray[i]) {Object obj = top100.first();top100.remove(obj);top100.add(inputArray[i]);}}//System.out.println(top100.toString());return top100;}public static void main(String[] args) {int numberCount = 100000000;//0;int maxNumber = numberCount;int inputArray[] = new int[numberCount];Random random = new Random();for (int i = 0; i < numberCount; ++i) {inputArray[i] = Math.abs(random.nextInt(maxNumber));}System.out.println("Sort begin...");long current = System.currentTimeMillis();Set<Integer> result = TreeSF.getTop100(inputArray);System.out.println("Spend time:"+ (System.currentTimeMillis() - current));}}class findValue {public static void main(String[] args){int max = 10000*1000;int length=100;int ints[] = new int[max];Random random = new Random();for (int i=0;i<max;i++) {ints[i]=Math.abs(random.nextInt(max));}List<Integer> list = new ArrayList();long start = System.currentTimeMillis();int size=0;int value=0;list.add(ints[0]);for(int i=1;i<max;i++){value=ints[i];size=list.size();if(value<list.get(size-1)){if(size<length){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<size;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<Integer> 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<Integer> 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++;}}}

热点排行