Title Description
Given a non-empty array of integers, in addition to an element appears only once, the rest of each element appears twice. To find out that only appears once in the elements.
Description:
Your algorithm should have linear time complexity. You can not use the extra space to achieve it?
Do not use the extra space, meaning space complexity is O (1), no matter what size data, you can find the target after a calculation.
Linear time complexity, time complexity is linear order O (n). The title meant little time as possible.
Example 1:
Input: [2,2,1]
Output: 1
Example 2:
Input: [4,1,2,1,2]
Output: 4
Interpretation of answers
1.
var singleNumber = function(nums) {
var res = nums[0];
for(var i=1;i<nums.length;i++){
res^=nums[i];
}
return res;
};
= ^ Is an exclusive OR means
When executed with: 60 ms
Memory consumption: 35.3 MB
2.
var singleNumber = function(nums) {
let map = new Map();
for(let i=0;i<nums.length;i++){
if(map.has(nums[i])){
map.set(nums[i], map.get(nums[i])+1);
}
else{
map.set(nums[i], 1);
}
}
for(let key of map.keys()){
if(map.get(key)==1){
return key;
}
}
return -1;
};
myMap.has (key) is used to detect the presence of the specified elements key.
When executed with: 68 ms
Memory consumption: 37.8 MB
3.
const singleNumber = nums => nums.reduce((prev, cur) => prev ^ cur);
For bit XOR operation
When performed with: 64 ms
Memory consumption: 35.3 MB
XOR
Exclusive OR (XOR) is a mathematical operator. It applies a logical operation. XOR mathematical symbol "⊕", computer symbol "xor". Algorithm which is:
a⊕b = (¬a ∧ - B) ∨ (A ∧¬b)
^: And (x ^ y) only when comparing two binary down to take an unequal, or take zero
14^15 (14 二进制 1110
15 二进制 1111
^与的结果 0001 ----》结果1)