Given an array of integers, every element appears three times except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
描述
数组内除了一个数外,其余数都出现 3 次,找出那个数
分析
以二进制的形式来考虑
一般方法:一个数出现 k 次,可以看成其二进制的第 i 位出现了 k 次,不论第 i 位是 0 或是 1,累加起来,取余 k 后,必定为 0,剩下的便是唯一的一个数
优化方法:不再将数细分成二进制的每一位,而是看作一个整体来统一处理。one,two,three 分别代表这个数出现的次数,three = (two & one) 相当于 3 = 2 + 1。~three 则相当于 three % 3,之后再更新 one 和 two 即可
代码
一般方法:
1 | public class Solution { |
优化方法:
1 | public class Solution { |