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
n = 7
ar = [1, 2, 1, 2, 1, 3, 2]
There is one pair of color 1 and one of color 2. There are three odd socks left, one of each color. The number of pairs is 2.
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
Input Format
The first line contains an integer n, the number of socks represented in ar.
The second line contains n space-separated integers, ar[i], the colors of the socks in the pile.
where
쉬운 문제이다. 알고리즘은 빈 리스트를 선언해서 해당 값이 존재하지 않으면 넣어주고 존재하면 존재하는 값을 리스트에서 삭제해주고 카운팅했다. 자바에서 더블 콜론과 map함수 사용이 익숙하지 않아 더 익혀야 할 것 같다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
private static int sockMerchant(int n, int[] numArray) {
List<Integer> numList = new ArrayList<Integer>();
int answer = 0;
for (Integer num : numArray) {
if (numList.contains(num)) {
numList.remove(num);
answer += 1;
} else {
numList.add(num);
}
}
return answer;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int[] numArray = Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
int answer = sockMerchant(n, numArray);
System.out.println(answer);
}
}