Problem Description:
Given an array of integers, every element appears twice except for one. Find the single one.
Note:
Your algorithm should has a linear runtime complexity. Could you implement it without using extra memory?
problem Analysis: linear time complexity is required, and it is best not to use extra space.
One, bit operation
An XOR operation that returns 1 only if the two bits are different. If the two numbers are the same, the XOR operation will return 0.
The nums contains only a single number, so, using an XOR operation, the last thing you get is the number you are seeking.
public int singlenumber (int[] nums) {
int single = 0;
for (int i = 0; i < nums.length; i + +)
Single = single ^ nums[i];
return single;
}
Second, HashSet
Compared to Hashtable,hashmap stored key-value key-value pairs, hashset directly manipulate objects and do not allow duplicate elements to be stored.
public int singlenumber (int[] nums) {
hashset<integer> set = new hashset<integer> ();
for (int i = 0; i < nums.length; i + +)
if (!set.add (Nums[i]))//Add Duplicate
Set.remove (Nums[i]); Delete duplicate elements
iterator<integer> Iterator = Set.iterator (); Iterator, traversing set
return Iterator.next ();
}
Single number Leetcode Java