import java.util.HashMap;
/**
* 137. 只出现一次的数字 II
* 给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现了三次。找出那个只出现了一次的元素。
* 说明:
* 你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?
* 示例 1:
* 输入: [2,2,3,2]
* 输出: 3
* 示例 2:
* 输入: [0,1,0,1,0,1,99]
* 输出: 99
*/
public class SingleNumber2 {
//使用位运算,不好理解
public static int singleNumber01(int[] nums){
int seeOnce = 0;
int seeTwice = 0;
for(int i: nums){
seeOnce = ~seeTwice & (seeOnce ^ i);
seeTwice = ~seeOnce & (seeTwice ^ i);
}
return seeOnce;
}
/**
* 使用额外的内存空间
* @param nums 传入的数组
* @return 数字
*/
public static int singleNumber02(int[] nums){
HashMap<Integer, Integer> map = new HashMap<>();
for(int i:nums){
map.put(i, map.getOrDefault(i ,0) +1);
}
for(int key: map.keySet()){
if(map.get(key) == 1){
return key;
}
}
return -1;
}
public static void main(String[] args){
int[] arr = {2, 2, 2, 3};
System.out.println(singleNumber02(arr));
System.out.println(singleNumber01(arr));
}
}