数组中出现一次的数字Ⅱ

问题陈述

思路分析

解法一

可考虑用一个HashMap来存,key为数字,value为出现次数。

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class SingleNumber {
public int getSingleNumber(int[] nums){
Map<Integer,Integer> map=new HashMap<>();
for(int c:nums) {
if (!map.containsKey(c)) {
map.put(c, 1);
continue;
} else {
map.put(c, map.get(c) + 1);
}
}
int result=0;
for(int key: map.keySet()){
if(map.get(key).equals(1)){
result=key;
break;
}
}
return result;
}
public static void main(String[] args){
int[] nums={3,4,3,3};
SingleNumber singleNumber=new SingleNumber();
System.out.println(singleNumber.getSingleNumber(nums));
}
}

解法二

代码实现

1
2
3
4
5
6
7
8
9
10
public int singleNumber(int[] nums) {
        //a为对应位的1出现2次的记录,b为对应位出现1次的记录,ab共同组成该位出现的次数
        int a = 0,b =0;
        for(int i:nums){
            b = ~a&(b^i);
            a = ~b&(a^i);
        }
        return b;
    }