Single Number II
来源:互联网 发布:mba与emba的区别 知乎 编辑:程序博客网 时间:2024/06/05 08:43
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?
思路:
这个解法是我看到最好的,最容易懂的解法。
Idea: if we look all the last bit of the numbers (assuming all are 32-bit) in the array, there must be 3k+1 or 3k `1's in total depending whether the single number's last bit is one or zero. This observation holds for all the rest 31 bits as well. Hence, if we sum all the numbers only at certain bit and mod by 3, we can get the corresponding bit the single number. Do this for all 32-bit, we can get all bits of that number. This generalizes the solution of LeetCode: Single Number I, where xor all the numbers is essentially trying to add all bits and then mod by 2...
就是 Int 32位,因为每个数字appear 3次,所以,每个位要么为3K+1,或者为3K.
取决于只出现一次的位是0,还是1.
这样思路就是取每一位相加,然后%3, 这样下来就是那个出现1次的数的位数,然后移动回去,加起来就是出现一次的数。
public class Solution { public int singleNumber(int[] A) { int single = 0; for(int i=0; i<32; i++){ int bit = 0; for(int j=0; j<A.length; j++){ bit += (A[j]>>i & 1); } bit = bit%3; single += bit<<i; } return single; } }
0 0
- Single Number & Single Number II
- Single Number & Single Number II
- Single Number II - leetcode
- Leetcode: Single Number II
- Single Number II
- Single Number II
- [LeetCode] Single Number II
- LeetCode: Single Number II
- leetcode -- Single Number II
- [leetcode]Single Number II
- [LeetCode] Single Number II
- 【leetcode】Single Number II
- Single Number I & II
- LeetCode:Single Number II
- Leetcode: Single Number II
- Single Number II
- leetcode :Single Number II
- Leetcode Single Number II
- OCP-1Z0-053-200题-114题-674
- [C#] 面向对象
- OCP-1Z0-053-200题-113题-158
- HBase 0.94 master启动过程源码分析
- CSBG群聊记录02(群号92210001)
- Single Number II
- style、 currentStyle、 runtimeStyle介绍
- 没有人能够一味地淡定,没有人能够一味地忍受
- DotnetBar在VS2010工具箱中不显示问题
- [C#]数组
- 不要去怨恨上天的不公平
- POJ 1284 Primitive Roots 原根(欧拉函数)
- 余弦的文章中的查询资料
- [C#] 字符串