CodeWars 코딩 문제 2021/01/15 - Find the unique number

이호현·2021년 1월 15일
0

Algorithm

목록 보기
51/138

[문제]

There is an array with some numbers. All numbers are equal except for one. Try to find it!

findUniq([ 1, 1, 1, 2, 1, 1 ]) === 2
findUniq([ 0, 0, 0.55, 0, 0 ]) === 0.55

It’s guaranteed that array contains at least 3 numbers.

The tests contain some very huge arrays, so think about performance.

This is the first kata in series:
1. Find the unique number (this kata)
2. Find the unique string
3. Find The Unique

(요약) 배열에서 유일한 수를 찾아라.

[풀이]

function findUniq(arr) {
  return arr.sort().filter(num => num === arr[0]).length > 1 ? arr[arr.length - 1] : arr[0]
}

숫자가 두가지로만 구성되어 있기 때문에 배열을 sort()하면 무조건 첫 요소나 마지막 요소는 다른 숫자가 된다.
정렬 후 첫 요소로 filter()를 사용해 배열 길이가 1보다 크면 같은 숫자가 여러개 있으니까 마지막 요소를 return하고, 아닐 경우 첫 요소를 return.

profile
평생 개발자로 살고싶습니다

0개의 댓글