Recommend Movie

题目是给一个List>,里面内容是[<用户名>, <电影名>, <评分>], 比如["小明", "哈利波特", "5"], 然后给你一个人名和这rating list,让你返回推荐这人看的movie list。满足的推荐条件有2个: 1是这人没看过这个movie,2是另外2个人有4或者5对这个movie的打分(打分在1-5)区间。

public class MovieRecommendation {

    public Set<String> findMovie(String[][] rating, String user)
    {
        // All movie List
        Set<String> movies = new HashSet<>();

        // user --> movie Set
        Map<String, Set<String>> userWatchedMovies = new HashMap<>();

        // Movie name  -- > who gives 4/5 on this movie
        Map<String, Set<String>> movieWithHighRatingCount  = new HashMap<>();


        for(int i = 0; i< rating.length; i++)
        {
            String userName = rating[i][0];
            String movieName = rating[i][1];
            int score = Integer.parseInt(rating[i][2]);

            // Add Movie name into total movie list
            movies.add(movieName);

            // Add movie into user watched list
            userWatchedMovies.putIfAbsent(userName, new HashSet<String>());
            userWatchedMovies.get(userName).add(movieName);

            // Update with high reating users of that movie
            movieWithHighRatingCount.putIfAbsent(movieName, new HashSet<String>());
            if(score > 3)
            {
                movieWithHighRatingCount.get(movieName).add(userName);
            }
        }

        Set<String> toWatchList = new HashSet<>();
        Set<String> userWatched = userWatchedMovies.get(user);
        for(String movie : movies)
        {
            if(!userWatched.contains(movie) && movieWithHighRatingCount.get(movie).size() >= 2)
            {
                toWatchList.add(movie);
            }
        
        }
        return toWatchList;
    } 
}

Last updated