Sales by Match

HeeSeong·2021년 6월 27일
0

HackerRank

목록 보기
1/18
post-thumbnail

🔗 문제 링크

https://www.hackerrank.com/challenges/sock-merchant/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=warmup


❔ 문제 설명


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

  • int: the number of pairs

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.


⚠️ 제한사항


  • 1n1001≤ n ≤ 100

  • 1ar[i]1001≤ ar[i] ≤ 100 where (0in)(0≤ i ≤ n)



💡 풀이 (언어 : Java)


쉬운 문제이다. 알고리즘은 빈 리스트를 선언해서 해당 값이 존재하지 않으면 넣어주고 존재하면 존재하는 값을 리스트에서 삭제해주고 카운팅했다. 자바에서 더블 콜론과 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);
    }
}
profile
끊임없이 성장하고 싶은 개발자

0개의 댓글