Question:
Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.
Follow up: Could you implement a solution with a linear runtime complexity and without using extra memory?
Example:
Input: nums = [2,2,1]
Output: 1
Input: nums = [4,1,2,1,2]
Output: 4
Input: nums = [1]
Output: 1
Source code
Version 1
Idea:
I need a pool to store elements, those are recorded by a counter. Hence, I remember one of LeetCode question I had done before. The question of Two Sum solution is map. A map container is supporting generic type key-value pairs with the templates.
Therefore, the elements of nums vector will be stored into map<int,int>, I set the element as a key (unique), give 1 as a value (means a counter). If the element is exist in map already, a counter will be added 1.
Finally, I use a loop to check each pairs whether a counter is equal to 1. Remember to return a key of pair.
Time complexity: O(n)
Space complexity: O(n)
1 | class Solution { |
Version 2
Idea:
This is an optimal algorithm that refered to internet. A Logical operator is very impressive method to solve it.
Exclusive or (XOR
) is one of a logicl operator that outputs is true (=1) only when two inputs differ. On the contrary, outputs is false (=0) only when the two inputs are the same.
E.g.,
1 0
XOR 1 0
0 0
Hence, we can do XOR for each elements and the result appears only once.
Time complexity: O(n)
Space complexity: O(1)
1 | class Solution { |