sweet1cris

Untitled

Feb 10th, 2018
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.56 KB | None | 0 0
  1.  
  2. public class Solution {
  3.     /**
  4.      * @param rating: the rating of the movies
  5.      * @param G: the realtionship of movies
  6.      * @param S: the begin movie
  7.      * @param K: top K rating
  8.      * @return: the top k largest rating moive which contact with S
  9.      */
  10.     public class Pair {
  11.         public int rating;
  12.         public int index;
  13.         public Pair(int rating, int index) {
  14.             this.rating = rating;
  15.             this.index = index;
  16.         }
  17.  
  18.     }
  19.    
  20.     public static Comparator<Pair> idComparator = new Comparator<Pair>(){
  21.         @Override
  22.         public int compare(Pair c1, Pair c2) {
  23.             return c2.rating - c1.rating;
  24.         }  
  25.     };
  26.     public void dfs(int[] rating, int[][] G,int x, int S, Queue<Pair> pq, boolean[] visit) {
  27.         if(visit[x] == true) {
  28.             return;
  29.         }
  30.         visit[x] = true;
  31.         if(x != S) {
  32.             pq.add(new Pair(rating[x], x));
  33.         }
  34.         for(int i = 0; i < G[x].length; i++) {
  35.             dfs(rating, G, G[x][i], S, pq, visit);
  36.         }
  37.     }
  38.    
  39.      
  40.     public int[] topKMovie(int[] rating, int[][] G, int S, int K) {
  41.         // Write your code here
  42.         Queue<Pair> pq =  new PriorityQueue<Pair>(K,idComparator);
  43.         boolean[] visit = new boolean[rating.length];
  44.         dfs(rating, G, S, S, pq, visit);
  45.         int[] ans = new int[K];
  46.         for(int i = 0; i < K; i++) {
  47.             if(!pq.isEmpty()) {
  48.                 Pair top = pq.poll();
  49.                 ans[i] = top.index;
  50.             }
  51.         }
  52.         return ans;
  53.     }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment