Advertisement
saurav_kalsoor

Help Mocha - JAVA

Sep 22nd, 2021
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.55 KB | None | 0 0
  1. package com.company;
  2.  
  3. import java.util.Arrays;
  4. import java.util.HashMap;
  5. import java.util.HashSet;
  6. import java.util.Scanner;
  7.  
  8.  
  9. public class Problem {
  10.  
  11.     public static void main(String[] args){
  12.         Scanner sc = new Scanner(System.in);
  13.         int n = sc.nextInt();
  14.         int[][] likes = new int[n][2];
  15.  
  16.         for(int i=0; i < n; i++){
  17.             likes[i][0] = sc.nextInt();
  18.             likes[i][1] = sc.nextInt();
  19.         }
  20.         int[] result_array = helpMocha(likes, n);
  21.         for(int a : result_array)
  22.             System.out.print(a + " ");
  23.         System.out.println();
  24.     }
  25.  
  26.  
  27.     public static int[] helpMocha(int[][] likes, int n) {
  28.         HashMap<Integer, HashSet<Integer>> mp = new HashMap<>();
  29.         HashSet<Integer> resultSet = new HashSet<>();
  30.  
  31.         for (int[] like : likes) {
  32.             if (!mp.containsKey(like[0])) {
  33.                 mp.put(like[0], new HashSet<>());
  34.             }
  35.             HashSet<Integer> temp = mp.get(like[0]);
  36.             temp.add(like[1]);
  37.             mp.put(like[0], temp);
  38.  
  39.             if (mp.containsKey(like[1]) && mp.get(like[1]).contains(like[0])) {
  40.                 resultSet.add(like[0]);
  41.                 resultSet.add(like[1]);
  42.             }
  43.         }
  44.        
  45.         if(resultSet.isEmpty())
  46.             return new int[]{-1};
  47.  
  48.         int[] result_array = new int[resultSet.size()];
  49.         int i=0;
  50.         for(int a : resultSet){
  51.             result_array[i] = a;
  52.             i++;
  53.         }
  54.  
  55.         Arrays.sort(result_array);
  56.         return result_array;
  57.     }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement