URL: https://leetcode.com/problems/single-number/

Описание

Учитывая непустой массив целых чисел nums, каждый элемент появляется дважды, кроме одного. Найди ту единственную.

Дополнительные сведения. Не могли бы вы реализовать решение с линейной сложностью времени выполнения и без использования дополнительной памяти?

Пример 1

Input: nums = [2,2,1]
Output: 1

Пример 2

Input: nums = [4,1,2,1,2]
Output: 4

Пример 3

Input: nums = [1]
Output: 1

Ограничения

  • 1 <= nums.length <= 3 * 104
  • -3 * 104 <= nums[i] <= 3 * 104
  • Каждый элемент в массиве появляется дважды, за исключением одного элемента, который появляется только один раз.

Решение:

Шаги

1. Create a object to keep track of the number of times a integer occurs in our nums array.
2. Loop through nums array. 
3. If there is no key in obj matching the corresponding integer, add the key to the obj Object, and assign it with the property 1.
4. If the corresponding integer is already has a key, matching its value, then increment the property of that key in obj.
5. Return the key in obj that has a property of 1.

Код (JavaScript)

Результаты

Runtime: 104 ms, faster than 29.24% of JavaScript online submissions for Single Number.
Memory Usage: 44.4 MB, less than 27.33% of JavaScript online submissions for Single Number.

Спасибо за просмотр. Если у вас есть отзывы о том, как улучшить этот код, оставьте комментарий.