Algorithm - lev1 폰켓몬

ryan·2022년 5월 23일
0

프로그래머스 level1 폰켓몬

N마리 폰켓몬의 종류 번호가 담긴 배열 nums가 매개변수로 주어질 때, N/2마리의 폰켓몬을 선택하는 방법 중, 가장 많은 종류의 폰켓몬을 선택하는 방법을 찾아, 그때의 폰켓몬 종류 번호의 개수를 return 하도록 solution 함수를 완성해주세요.

내 풀이 (100/100)

function solution(nums) {
  const numsLength = nums.length / 2;
  const set = new Set(nums);
  const arraySet = Array.from(set);
  if (numsLength >= arraySet.length) {
    return arraySet.length;
  } else return numsLength;
}
  • Set api와 array.from을 활용하여 중복값을 제외한 배열을 반환시켜 정답을 추출했다.

다른 풀이

function solution(nums) {
  const numLen = nums.length;
  const setLen = [...new Set(nums)].length;
  return numLen / 2 >= setLen ? setLen : numLen / 2;
}
  • spread operator를 사용하여 배열의 길이를 바로 추출한 뒤 length를 비교했다.
profile
프론트엔드 개발자

0개의 댓글