Problem
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 .
Function Description
Complete the sockMerchant function in the editor below. It must return an integer representing the number of matching pairs of socks that are available.
sockMerchant has the following parameter(s):
- n: the number of socks in the pile
- ar: the colors of each sock
Input Format
The first line contains an integer , the number of socks represented in .
The second line contains space-separated integers describing the colors of the socks in the pile.
Constraints
- where
Output Format
Print the total number of matching pairs of socks that John can sell.
Sample Input
9
10 20 20 10 10 30 50 10 20
Sample Output
3
Explanation
John can match three pairs of socks.
How I solve the problem
# 10은 10끼리 처럼 짝꿍을 지어서 양말을 모으는 것이 문제
# Java에는 Arrays.sort를 사용해서 input의 배열들을 오름차순으로 정렬해서 같은 짝이 있으면 count를 더하고 for문의 i에 1을 더 더해서 짝지어진 양말을 또 다른 양말과 짝지어지지 않도록 하는 것이 핵심
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 | import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.regex.*; public class Solution { // Complete the sockMerchant function below. static int sockMerchant(int n, int[] ar) { int result = 0; Arrays.sort(ar); for (int i = 0; i < n - 1; i++) { if (i < n && ar[i] == ar[i + 1]) { result++; i = i + 1; } } return result; } private static final Scanner scanner = new Scanner(System.in); public static void main(String[] args) throws IOException { BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); int n = scanner.nextInt(); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); int[] ar = new int[n]; String[] arItems = scanner.nextLine().split(" "); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); for (int i = 0; i < n; i++) { int arItem = Integer.parseInt(arItems[i]); ar[i] = arItem; } int result = sockMerchant(n, ar); bufferedWriter.write(String.valueOf(result)); bufferedWriter.newLine(); bufferedWriter.close(); scanner.close(); } } | cs |
[출처 : https://www.hackerrank.com ]
'1 Day 1 Algorithms' 카테고리의 다른 글
[2018.12.13] Counting Valleys (0) | 2018.12.14 |
---|---|
[2018.12.13] Compare the Triplets (0) | 2018.12.14 |
[2018.12.12] Simple Array Sum (0) | 2018.12.14 |
[2018.12.11] Solve Me First (0) | 2018.12.14 |
1일 1알고리즘 문제 풀기 Start (0) | 2018.12.14 |
댓글