본문 바로가기
알고리즘/Codewars

[Codewars] Find the unique number (6 kyu) / JavaScript

by fluss 2023. 1. 5.

https://www.codewars.com/kata/585d7d5adb20cf33cb000235

 

Codewars - Achieve mastery through coding practice and developer mentorship

A coding practice website for all programming levels – Join a community of over 3 million developers and improve your coding skills in over 55 programming languages!

www.codewars.com

 

DESCRIPTION:

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) {
  const set = [...new Set(arr)];
  const check = [0, 0];
  let result = 0;
  for(let i = 0; i < arr.length; i++){
    if(arr[i] === set[0]){
      check[0]++;
      if(check[0] > 1){
        result = set[1];
        break;
      }
    }else{
      check[1]++;
      if(check[1] > 1){
        result = set[0];
        break;
      }
    }
  }
  return result;
}

댓글