HackerRank Sales By Match

1. 문제

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.

Constraints

where
Sample Input

STDIN Function


9 n = 9
10 20 20 10 10 30 50 10 20 ar = [10, 20, 20, 10, 10, 30, 50, 10, 20]
Sample Output

3
Explanation

sock.png

There are three pairs of socks.

1.1. 컴퓨팅적 사고

색상별로 짝을 맞추는 양말더미에서 짝의 개수가 맞는것의 개수를 찾는 문제이다.
가장 핵심은 같은값을 가지는 값의 개수를 세준후에 해당 되는 값의 개수에서 / 2로 나누어주면 해당되는 양말의 짝의 개수를 모두 구해나갈 수 있다. 시간복잡도는 O(N) 선형시간으로 처리가 가능하다. N의 범위가 100까지 이므로 완전탐색 N^3의 로직까지 구현해낼 수 있을것으로 생각한다.

1.2. 소스코드

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
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

class Result {

/*
* 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
*/

public static int sockMerchant(int n, List<Integer> ar) {
// Write your code here
int[] arr = new int[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;
}
}

public class Solution {
public static void main(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());

int result = Result.sockMerchant(n, ar);

bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();

bufferedReader.close();
bufferedWriter.close();
}
}