Single Number II
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?
思路:
数组中只有一个数只出现一次,其他数都出现三次,题目要求用线性时间复杂度算法找出这个数。这道题比Single Number要难一些。
考虑用统计的思路来解这道题,如果一个数出现了三次就消掉,int的32个位都是由0/1组成的,所以将所有数的对应位加起来,再将各位的统计和对3取模,最终剩下的结果就是要找出的数。如图示意(以4位为例)
考查知识点:位运算
难度 : ★ ★ ★ ☆ ☆
初级解法
用一个数组int count[32]
,数组中count[i]
代表第i位的当前统计值。对于每一个A[i]
,通过移位运算获得