알고리즘/HackerRank

Sales by Match

webmaster 2021. 11. 18. 17:20
728x90

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

 

Sales by Match | HackerRank

How many pairs of socks can Alex sell?

www.hackerrank.com

 

  • 문제
    • 문제
    • 같은 숫자 개수가 짝으로(2개) 몇 개의 묶음이 있는지 계산해 주는 문제이다.

풀이

  • Map의 선언하여 해당 숫자의 개수가 몇 개 인지를 저장한다.
  • Map의 돌면서 숫자의 개수(value)를 2로 나눈 값을 결괏값에 더해준다.
  • private static int sockMerchant(int n, List<Integer> ar) {
      Map<Integer,Integer> map = new HashMap<>();// 숫자 : 갯수
      for(int num : ar){
      map.put(num,map.getOrDefault(num,0)+1); // 갯수가 있을 경우 : 갯수 +1 , 없을 경우 갯수 : 0 + 1
      }
      int answer = 0;
      for(int key : map.keySet()){
      answer += map.get(key)/2; //갯수를 2로 나눈 값을 더해준다.
      }
      return answer;
    }
728x90

'알고리즘 > HackerRank' 카테고리의 다른 글

Arrays Left Rotation  (0) 2021.11.18
2D Array - DS  (0) 2021.11.18
Repeated String  (0) 2021.11.18
Jumping on the Clouds  (0) 2021.11.18
Counting Valleys  (0) 2021.11.18