We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Simple
1) Fill array
2) Add Distinct elements in hashmap from array as below
Hashmap contain key as element and value as count of elements in the array
3) then divide count of elements by 2 and print
import java.util.*;
public class SocksPair {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
int[] array = new int[T];
for (int i = 0; i < T; i++) {
array[i] = sc.nextInt();
}
HashMap<Integer, Integer> pair = checkpair(array);
Integer parCount = countandPrintpair(pair);
System.out.println(parCount);
}
private static Integer countandPrintpair(HashMap<Integer, Integer> pair) {
int paircount = 0;
for (Integer key : pair.keySet()) {
Integer thisCount = pair.get(key) / 2;
paircount += thisCount;
}
return paircount;
}
private static HashMap<Integer, Integer> checkpair(int[] array) {
Arrays.sort(array);
/* for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}*/
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < array.length; i++) {
if (map.containsKey(array[i])) {
map.put(array[i], map.get(array[i]) + 1);
} else {
map.put(array[i], 1);
}
}
return map;
}
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Sales by Match
You are viewing a single comment's thread. Return to all comments →
Simple 1) Fill array 2) Add Distinct elements in hashmap from array as below Hashmap contain key as element and value as count of elements in the array 3) then divide count of elements by 2 and print
import java.util.*;
public class SocksPair {
}