Movie Network

https://www.lintcode.com/problem/movie-network/description

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Solution {
    /**
     * @param rating: the rating of the movies
     * @param G: the realtionship of movies
     * @param S: the begin movie
     * @param K: top K rating
     * @return: the top k largest rating moive which contact with S
     */
    public int[] topKMovie(int[] rating, int[][] G, int S, int K) {
        // Write your code here
        List list = new ArrayList<>();
        int[] ints = G[S];
        for (int i = 0; i < ints.length; i++) {
            int anInt = ints[i];
            if (anInt != S && !list.contains(anInt)) {
                list.add(anInt);
            }
        }
        for (int i = 0; i < list.size(); i++) {
            Integer integer = list.get(i);
            int[] ints1 = G[integer];
            for (int j = 0; j < ints1.length; j++) {
                int anInt = ints1[j];
                if (anInt != S && !list.contains(anInt)) {
                    list.add(anInt);
                }
            }
        }
        if (list.size() > K) {
            Collections.sort(list, new Comparator() {
                @Override
                public int compare(Integer o1, Integer o2) {
                    return rating[o2] - rating[o1];
                }
            });
            int[] res = new int[K];
            for (int i = 0; i < res.length; i++) {
                res[i] = list.get(i);
            }
            return res;
        } else {
            int[] res = new int[list.size()];
            for (int i = 0; i < res.length; i++) {
                res[i] = list.get(i);
            }
            return res;
        }

    }
}

你可能感兴趣的:(Movie Network)