原题
https://leetcode-cn.com/problems/single-number-ii/
思路
1. 常规思路 hash
,不做过多的描述
2. 应该能想到使用位运算
先贴一张大致思路图
2.1 对于nums
中每个数字的每一位单独进行计算,累加得到count
2.2 对于count
进行%3
的操作,其结果一定为0或者1,0或者1其实就是当前位的值
2.3 对于所有位进行计算完毕,每个位的结果拼接到一起,得到的就是需要的结果只出现了一次的元素
题解
package cn.codemao.botmao.admin;
/**
* @version 1.0
* @author: zhangkun@codemao.cn
* @description:
* @create: 2021-04-30 10:40
**/
public class Code137 {
public static void main(String[] args) {
int[] nums = {43,16,45,89,45,-2147483648,45,2147483646,-2147483647,-2147483648,43,2147483647,-2147483646,-2147483648,89,-2147483646,89,-2147483646,-2147483647,2147483646,-2147483647,16,16,2147483646,43};
int res = singleNumber(nums);
System.out.println(res);
}
public static int singleNumber(int[] nums) {
int len = nums.length;
int res = 0;
// 循环32位
for (int i = 0; i < 32; i++) {
int count = 0;
// 循环每一个数字
for (int j = 0; j < len; j++) {
// 计算每一个数字末位是否为1,为1的话则累加
count += ((nums[j] >> i) & 1);
}
// 当前位的所有数字计算完毕
// 计算count%3,结果为0或者1
// 疑问:结果不可能是2吗?
// 解答:不可能为2,因为count在累加的时候,都是累加1或者0的,
// 并且这些数字一定是3个,所以就是3个1,或者3个0,最后还要有那个多余出来的数字
if (count % 3 == 1) {
// 1逐步左移,得到对应位的结果数字
// 然后与res进行或运算,运算之前res对应的位一定是0,结合0|1=1的特性,所以使用或运算
res |= (1 << i);
}
}
return res;
}
}