返回共同好友最多的K个好友推荐input: Personreturn
Listclass person{String id;Set friends;}
用pq 更快些
Comparator<Map.Entry<Integer, Integer>> comp = new Comparator<Map.Entry<Integer, Integer>>() { public int compare(Map.Entry<Integer, Integer> entry1, Map.Entry<Integer, Integer> entry2) { return entry1.getValue() - entry2.getValue(); } }; PriorityQueue<Map.Entry<Integer, Integer>> minHeap = new PriorityQueue<Map.Entry<Integer, Integer>>(11, comp); for (Map.Entry<Integer, Integer> each : freqMap.entrySet()) { minHeap.offer(each); if (minHeap.size() > k) minHeap.pop(); } for (int i=1; i<=k; i++) { res.add(minHeap.poll().getKey()); } return res;
public Person mostMutualFriend(Person p){ Map<String, Integer> map = new HashMap<String, Integer>(); int max = 0; Person res = null; for(Person friend : p.friends){ for(Person ff : friend.friends){ if(ff.id.equals(p.id))continue; //不能推荐自己!!!!!!!!!!! if(Map.containsKey(ff.id)){ map.put(ff,map.get(ff.id)+1); if(map.get(ff.id)+1>max) max = map.get(ff.id)+1; res = ff; } else{ map.put(ff.id,1); if(1>max) max = 1; res = ff; } } } return res; } class Item{ int count; String id; } //reecommend K new friends to p public List<String> recommendKNewfriend(Person p, int k){ Map<String,Integer> p_f = new HashMap<String,Integer>(); //potential friend for(Person friend : p.friends){ for(Person x: friend.friends){ if(x.id.equals(p.id)||p.friends.contains(x)) continue; //x is the person p knows map.put(x.id,map.getOrDefault(x.id,0)+1); } } Item x[] = new Item[p_f.size()]; //pq 也可以 min-heap int index = 0; for(String id : p_f.keySet()){ x[index++] = new Item(p_f.get(id),id); } quickSelect(x,0,x.length-1,k); List<String> res = new ArrayList<String>(); for(int i = 0; i<k;i++){ res.add(x[i].id); } return res; } public void quickSelect(Item[] item, int i, int j,int k){ int pivot = item[j].count; int index = i; for(int k = i; k<j;k++){ if(item[k].count>pivot) swap(item,k,index++); } swap(item,j,index); if(index==k-1){ return; } else if(index>k-1){ quickSelect(item,i,index-1,k); } else{ quickSelect(item,index+1,j,k); } }