出现3次的数组中寻找出现一次的数字

题目

https://leetcode-cn.com/problems/shu-zu-zhong-shu-zi-chu-xian-de-ci-shu-ii-lcof

解法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class SO56_singleNumber2 {

public int singleNumber(int[] nums) {
int[] counts = new int[32];
for (int num : nums) {
for (int j=0; j<32; j++) {
counts[j] += (num&1);
num >>=1;
}
}
int res=0, m=3;
for (int i=0; i<32; i++) {
res <<= 1;
res |= counts[31-i] % m;
}
return res;
}
}
1
2
3
4
5
6
7
8
9
10
class Solution {
public int singleNumber(int[] nums) {
int ones = 0, twos = 0;
for(int num : nums){
ones = ones ^ num & ~twos;
twos = twos ^ num & ~ones;
}
return ones;
}
}
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×