Created
January 30, 2023 10:02
-
-
Save p0rsche/e3596ffa358b41233863fd7fb1bdcedd to your computer and use it in GitHub Desktop.
Find unique number in the array of numbers where all except one have duplicates
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Дан массив из чисел | |
* Все значения, кроме одного, повторяются. | |
* Найти уникальное значение за O(n). | |
* Известно, что уникальное значение одно и только одно | |
* Пример: | |
* Вход: [5,9,6,1,9,6,5] | |
* Выход: [1] | |
* | |
*/ | |
// Решение с XOR показалось наиболее классным. Если нужен ответ в виде массива, просто поменяйте вывод функции | |
// Напомню про XOR: x ^ 0 = x, x ^ x = 0 | |
const findUnique = a => a.reduce((acc, cur) => acc ^ cur) | |
console.log(findUnique([5,9,6,1,9,6,5])) | |
// 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment