ahribori / daily-algorithm

매일 알고리즘 문제풀자
1 stars 1 forks source link

Sock Merchant #20

Open ahribori opened 5 years ago

ahribori commented 5 years ago

https://www.hackerrank.com/challenges/sock-merchant/problem

ahribori commented 5 years ago
const sockMerchant = (n, ar) => {
  const set = new Set();
  let count = 0;

  ar.forEach(item => {
    if (!set.has(item)) {
      set.add(item);
    } else {
      count++;
      set.delete(item);
    }
  });

  return count;
};

test('solution', () => {
  expect(sockMerchant(9, [10, 20, 20, 10, 10, 30, 50, 10, 20])).toBe(3);
});
SriSwathi25 commented 5 years ago

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) {
    Set<Integer> color=new HashSet<Integer>();
    int pairs=0;
    for(int i=0;i<n;i++)
    {
        if(!color.contains(ar[i]))
        color.add(ar[i]);
        else
        {
            pairs++;
            color.remove(ar[i]);
        }
    }
    return pairs;

}

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();
}

}