Algorithm

[백준] 11652 카드(JS)

createElement 2022. 8. 10. 12:30

 

 

11652번: 카드

준규는 숫자 카드 N장을 가지고 있다. 숫자 카드에는 정수가 하나 적혀있는데, 적혀있는 수는 -262보다 크거나 같고, 262보다 작거나 같다. 준규가 가지고 있는 카드가 주어졌을 때, 가장 많이 가지

www.acmicpc.net

 

수가 2의 62제곱까지 주어질 수 있으므로 모든 수를 BigInt로 변환해야 한다.

 

또한 Map을 사용해 주어진 수와 그에 따른 개수를 저장한다.

 

정렬은 sort 메서드를 이용하여 다음 코드와 같이 BigInt를 정렬하면 에러가 발생한다.

-> 이는 sort 메서드 내부에 직접 비교 조건문을 작성해 해결할 수 있다.

 

const big = [1n, 2n, 3n, 4n];
big.sort((a,b) => a - b);
console.log(big);
// Error: Cannot convert a BigInt value to a number

 

 

Array sorting is broken with Bigint In JS?

It seems like Array.prototype.sort() is broken with BigInt This works const big = [1n, 2n, 3n, 4n]; big.sort(); console.log(big); // expected output: Array [1n, 2n, 3n, 4n] But this doesn't :( con...

stackoverflow.com

 

최종 코드

function solution(N, input) {
  input = input.map(BigInt);
  let map = new Map();
  for (let i = 0; i < N; i++) {
    let card = input[i];
    let isExist = map.get(card);
    if (isExist) {
      map.set(card, isExist + 1);
    } else {
      map.set(card, 1);
    }
  }
  let sorted = [...map].sort((a, b) => {
    if (b[1] < a[1]) return -1;
    else if (b[1] > a[1]) return 1;
    else {
      if (a[0] < b[0]) return -1;
      if (a[0] > b[0]) return 1;
      else return 0;
    }
  });
  return sorted[0][0].toString();
}

console.log(solution(5, [1, 2, 1, 2, 1])); // 1
console.log(solution(6, [1, 2, 1, 2, 1, 2])); // 1