algorithm-base/animation-simulation/求次数问题/只出现一次的数2.md

115 lines
5.2 KiB
Java
Raw Normal View History

2021-03-20 08:44:27 +00:00
> **[tan45du_one](https://raw.githubusercontent.com/tan45du/tan45du.github.io/master/个人微信.15egrcgqd94w.jpg)** ,备注 github + 题目 + 问题 向我反馈
>
>
>
> <u>[****](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u> 两个平台同步,想要和题友一起刷题,互相监督的同学,可以在我的小屋点击<u>[**刷题小队**](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u>进入。
#### [137. II](https://leetcode-cn.com/problems/single-number-ii/)
2021-03-19 07:35:25 +00:00
>
1:
> : [2,2,3,2]
> : 3
2:
> : [0,1,0,1,0,1,99]
> : 99
###
####
OK
1. HashSet
2.SumSet * 3 - SumNum/ 2 2 2
####
```java
class Solution {
public int singleNumber(int[] nums) {
HashSet<Integer> set = new HashSet<>();
long sumset = 0;
long sumnum = 0;
for (int x : nums) {
//所有元素的和
sumnum += x;
if (set.contains(x)) {
continue;
}
//HashSet元素和
sumset += x;
set.add(x);
}
//返回只出现一次的数
return (int)((3 * sumset - sumnum) / 2);
}
}
```
HashMap
###
####
![2](https://cdn.jsdelivr.net/gh/tan45du/tan45du.github.io.photo@master/photo/只出现一次的数字2.5p4wxbiegxc0.png)
3 1 1 2 3 3 +1 3 +1
####
```java
class Solution {
public int singleNumber(int[] nums) {
int res = 0;
for(int i = 0; i < 32; i++){
int count = 0;
for (int j = 0; j < nums.length; j++) {
//先将数右移,并求出最后一位为 1 的个数
if ((nums[j] >> i & 1) == 1) {
count++;
}
}
//找到某一位取余为 1 的数,并左移,为了将这一位循环结束后移至原位
if (count % 3 != 0) {
res = res | 1 << i;
}
}
return res;
}
}
```
> **<<** **<<** 0
>
> **>>** ">>"**>>**
a & 1 a | 1
> **&** ,1,1,0
![](https://cdn.jsdelivr.net/gh/tan45du/tan45du.github.io.photo@master/photo/只出现一次的数位运算且.vq3lcgv0rbk.png)
a & 1 1 1 0 a & 1 a 1 a 1 a & 1 = 1, 0 a
> **|** 11
![](https://cdn.jsdelivr.net/gh/tan45du/tan45du.github.io.photo@master/photo/或运算.6orep3gsrxc0.png)
res 0 1 1