Recommend Friends

weixin_34365417發表於2018-05-24

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();
    }
}