Recommend Friends
https://www.lintcode.com/problem/recommend-friends/description
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class Solution {
/**
* @param friends: people's friends
* @param user: the user's id
* @return: the person who most likely to know
*/
public int recommendFriends(int[][] friends, int user) {
// Write your code here
int[] friendArr = friends[user];
Set<Integer> set = new HashSet<>();
for (int i = 0; i < friendArr.length; i++) {
int i1 = friendArr[i];
set.add(i1);
}
Map<Integer, Integer> map = new HashMap<>();
Iterator<Integer> iterator = set.iterator();
while (iterator.hasNext()) {
Integer next = iterator.next();
int[] friend = friends[next];
for (int i = 0; i < friend.length; i++) {
int i1 = friend[i];
if (i1 != user && !set.contains(i1)) {
Integer integer = map.get(i1);
if (integer == null) {
integer = 1;
} else {
integer++;
}
map.put(i1, integer);
}
}
}
Set<Map.Entry<Integer, Integer>> entries = map.entrySet();
if (entries.isEmpty()) {
return -1;
}
List<Map.Entry<Integer, Integer>> entryList = new ArrayList<Map.Entry<Integer, Integer>>
(entries);
Collections.sort(entryList, new Comparator<Map.Entry<Integer, Integer>>() {
@Override
public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {
return o2.getValue() - o1.getValue();
}
});
return entryList.get(0).getKey();
}
}
相關文章
- 新建recommend分支
- D - New Friends
- 825. Friends Of Appropriate AgesAPP
- [LeetCode] 825. Friends Of Appropriate AgesLeetCodeAPP
- mORMot and Open Source friends SynProject Tutorial (SynProject教程)ORMProject
- King是如何打造三消新秀《Candy Crush Friends Saga》?
- 黑客竊取了超過 2 億個 Zynga“Words with Friends”玩家資料黑客
- Ubuntu 更換新 Logo :橙色+矩形 Logo|“Circle of Friends”主題更緊湊更統一UbuntuGo