John works at a clothing store. He has a large pile of socks that he must pair by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are.

For example, there are  socks with colors . 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 .

 

Sample Input

9

10 20 20 10 10 30 50 10 20

Sample Output

3

 

 

배열안에 숫자들이 들어오는데 양말처럼 짝을 지어서 몇 짝이 나오는지 반환하는 문제이다.

 

 

static int sockMerchant(int n, int[] ar) {
	int result = 0;
	HashSet<Integer> colors = new HashSet<Integer>();

	for(int i = 0; i < ar.length ; i++){
		if(!colors.contains(ar[i])){
			colors.add(ar[i]);
		}else{
			result++;
			colors.remove(ar[i]);
		}
	}
	return result;
}

HashSet에 하나씩 담으면서 중복데이터가 있을경우 수량을 ++ 하고, 해당 요소를 제거하는 방법이다. 

시간복잡도 O(1)

+ Recent posts