首页 > 代码库 > [LeetCode] Single Number II
[LeetCode] 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?
Answer: 这个算法的思路,就是数每一位上1的个数综合。既然有假设共有3n+1个数字,如果单例数字中的这一位为1,那么最终这一位的1的个数肯定为3k+1,k为某一整数。
最直白的思路是直接对数组进行遍历,然后对没一个元素进行位操作,最后让每个个数对3求余。其实没有那么麻烦。既然是对3求余,那么我们可以直接用3个数做位标记,看该位上1出现了0次1次2次还是3次?如果出现了3次,那么直接清零即可。
下面直接插入代码:
public class Solution { public int singleNumber(int[] A) { int one = 0; // the first time int two = 0; // the second time int three = 0; // the third time for (int i=0; i<A.length; i++) { three = two & A[i]; two = two | A[i] & one; one = one | A[i]; one = one & ~three; two = two & ~three; } return one; }}
[LeetCode] Single Number II
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。