1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
| class Solution { int count = 0; public int unhappyFriends(int n, int[][] preferences, int[][] pairs) { for (int i = 0; i < n/2; i++) { isUnHappy(n, preferences, pairs, i, 0); isUnHappy(n, preferences, pairs, i, 1); } return count; }
public void isUnHappy(int n, int[][] preferences, int[][] pairs, int i, int j){ int self = pairs[i][j];
int friend; if (j == 0) { friend = pairs[i][1]; }else { friend = pairs[i][0]; }
List<Integer> selfMoreSweetFriend = findMoreSweetFriends(n, preferences, self, friend);
for (int k = 0; k < selfMoreSweetFriend.size() ; k++) { int sweet = selfMoreSweetFriend.get(k); int matchFriend = findFriend(pairs, sweet); List<Integer> matchMoreSweetFriend = findMoreSweetFriends(n, preferences, sweet, matchFriend); if (matchMoreSweetFriend.contains(self)){ count++; break; } } }
public List<Integer> findMoreSweetFriends(int n, int[][] preferences, int self, int matchFriend){ List<Integer> list = new ArrayList<Integer>(); for (int k = 0; k < n - 1; k++) { if (preferences[self][k] == matchFriend) { break; } list.add(preferences[self][k]); } return list; }
public int findFriend(int[][] pairs, int sweet){ for (int i = 0; i < pairs.length; i++) { if (pairs[i][0] == sweet) { return pairs[i][1]; } if (pairs[i][1] == sweet) { return pairs[i][0]; } } return -1; } }
|