Method 1: Use hashMap
Scan again to record the number of occurrences of each element. Scan again to retrieve the key with value=1.
class Solution {
public int singleNumber(int[] nums) {
Map<Integer, Integer> map = new HashMap<>();
for (int num : nums) {
if(! map.containsKey(num)) { map.put(num,1);
} else {
map.put(num, map.get(num) + 1); }}for (int k : map.keySet()) {
if (map.get(k) == 1) {
returnk; }}return 0; }}Copy the code
Method two: bit operation
- Any number and 0 xor, the result is still the original number, i.e
A radius 0 = a
- Any number xor with itself, the result is 0, i.e
A radius of a = 0
- Xor operations satisfy commutative and associative laws,
A ⊕ B ⊕ A = B ⊕ A = B ⊕(A ⊕ A) = B ⊕0 = B
Scan through and double or double every number, and you end up with a number that only appears once.
class Solution {
public int singleNumber(int[] nums) {
int res = 0;
for (int num : nums) {
res = res ^ num; // xor ^
}
returnres; }}Copy the code