There is a large pile of socks that must be paired by color. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are.
Example
There is one pair of color and one of color . There are three odd socks left, one of each color. The number of pairs is .
Function Description
Complete the sockMerchant function in the editor below.
sockMerchant has the following parameter(s):
int n: the number of socks in the pile
int ar[n]: the colors of each sock
Returns
int: the number of pairs
Input Format
The first line contains an integer , the number of socks represented in .
The second line contains space-separated integers, , the colors of the socks in the pile.
색상별로 짝을 맞추는 양말더미에서 짝의 개수가 맞는것의 개수를 찾는 문제이다.
가장 핵심은 같은값을 가지는 값의 개수를 세준후에 해당 되는 값의 개수에서 / 2로 나누어주면 해당되는 양말의 짝의 개수를 모두 구해나갈 수 있다. 시간복잡도는 O(N) 선형시간으로 처리가 가능하다. N의 범위가 100까지 이므로 완전탐색 N^3의 로직까지 구현해낼 수 있을것으로 생각한다.
/* * Complete the 'sockMerchant' function below. * * The function is expected to return an INTEGER. * The function accepts following parameters: * 1. INTEGER n * 2. INTEGER_ARRAY ar */
publicstaticintsockMerchant(int n, List<Integer> ar){ // Write your code here int[] arr = newint[101]; for(int i=0; i<ar.size(); i++){ arr[ar.get(i)]++; } int answer = 0; for(int i : arr){ if(i != 0){ answer += (i/2); } } return answer; } }
publicclassSolution{ publicstaticvoidmain(String[] args)throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int n = Integer.parseInt(bufferedReader.readLine().trim());
List<Integer> ar = Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" ")) .map(Integer::parseInt) .collect(toList());