标签:
同学在群里发了一到笔试题:
一个int数组里面有100个随机数,这些数中有重复的,请找出这100个数中每个不重复的数的重复次数。
恩,大概就是这么个意思。。
当时想了想,得出个List<Map<String,int>>这么个解决方法,思想就是从数组第一个元素开始遍历,然后将结果放到Map里面
具体操作就是:
数据:int[100]={1,2,2,1,2,132,1321,1,23,2,1,2,...}
step 1: new Map<1,1>
step 2: new Map<2,1>
step 3: find(Map.key==2) then (Map.value)++
就是这么个思想啦。。。
然后就实践了下,本来以为10多分钟就能搞定,没想到前前后后弄了1个小时。。羞。。
public class Founder {
static int xx = 1;
private List<Map<String, Integer>> mFunction(int n[]) {
List<Map<String, Integer>> mList = new ArrayList<Map<String, Integer>>();
HashMap<String, Integer> mMap;
int target = -1;
int counter = 1;
String targetKey=null , counterKey=null;
for (int x : n) {
if (mList.isEmpty()) {
mMap = new HashMap<String, Integer>();
mMap.put("target"+ x, x);
mMap.put("counter" + x, counter);
mList.add(mMap);
} else {
boolean flag = false;
for (int i = 0;i < mList.size();i++,target = -1 , targetKey = "",counterKey="") {
mMap = (HashMap<String, Integer>) mList.get(i);
Set mSet = mMap.keySet();
Iterator it = mSet.iterator();
while(it.hasNext()){
String temp = (String)it.next();
char c = temp.charAt(0);
if(c==‘t‘){
targetKey = temp;
counterKey = (String)it.next();
}else{
counterKey = temp;
targetKey = (String)it.next();
}
}
target = mMap.get(targetKey);
counter = mMap.get(counterKey);
if(target == x){
++counter;
mMap.put("counter" + target, counter);
flag = true;
}
xx++;
}
if(!flag){
counter = 1;
mMap = new HashMap<String, Integer>();
mMap.put("target"+ x, x);
mMap.put("counter" + x, counter);
mList.add(mMap);
}
}
}
return mList;
}
public static void main(String[] args) {
int test1n[]={1,1,1,1,3,2,2,3,2,2,3};
int test2n[] = new int[100000];
for(int i = 0;i<test2n.length;i++){
test2n[i] = (int)(Math.random()*10);
}
List<Map<String, Integer>> mList = new Founder().mFunction(test2n);
for(int x : test2n){
System.out.print(x+" ");
}
System.out.println();
for(int i = 0;i < mList.size();i++){
HashMap<String, Integer> mMap = (HashMap<String, Integer>) mList.get(i);
Set<String> set = mMap.keySet();
Iterator<String> it = set.iterator();
while(it.hasNext()){
String key = it.next();
int value = mMap.get(key);
System.out.print(key+":"+value+" ");
}
System.out.println();
}
System.out.println(xx);
}
}
哈哈哈哈,没注释!!!
是的,就是没注释,掌握思想就OK啦。。。(其实是偷懒啊。。不规范啊。。。八嘎)
最后想了下大数据量怎么办。。其实就是这点让我有了记录下这个算法的想法,如果原始数据是1W,10W。。1亿呢。。。WTF
瞬间就想到了cache块哈哈哈,感觉很好玩啊,弄个原始数据10%的cache块,用用FIFO..LRU什么的搞搞命中算不算是一种优化呢
有时间再玩啦,话说除了面试题,谁TM还数字符玩呢。。
还有,同学想到的方法是先排序,在遍历计数,貌似也OK啦,不过是要用到什么二分之类的来做可能比较快,他说他用冒泡。。。笑嘻嘻
MRAK下,安智笔试题是数字符串中的字符,同理同理,当初自己还是用两个for循环来搞,羞羞。。。
最后最后,测试代码均是自然数,没有测试过负数,应该没多差吧,还有,测试了次10W数据量,弄完貌似用了90+W次遍历,主要是因为Map的KeySet越来越长的缘故,加个cache块应该会好很多。
用2for的话OMG,用冒泡的话。。OMG,用二分的话。。不知道了O(nlogn)?WTF?蛋疼的时候再搞
各位看官,转载说明,Thanks
还有有更好的方法的话可以尽情甩脸啊!!!
标签:
原文地址:http://www.cnblogs.com/H-Col/p/4400964.html