LeetCode OJ平台上Single Number II题目使用java位运算解决
2014-06-11 21:55
369 查看
原题如下,不让用extra memory,那么哈希什么的就不要考虑了。
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?
在大神们的指导下,这个问题用java位运算就可以轻松解决。
如果某个数字出现三次,二进制格式下,三个数字的第0位相加%3==0,第1位相加%3==0,第......
所以把所有数字考虑成二进制格式,每一位相加,然后%3,结果就是只出现一次的数字了。
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?
在大神们的指导下,这个问题用java位运算就可以轻松解决。
如果某个数字出现三次,二进制格式下,三个数字的第0位相加%3==0,第1位相加%3==0,第......
所以把所有数字考虑成二进制格式,每一位相加,然后%3,结果就是只出现一次的数字了。
public class Solution { public static int singleNumber(int[] A) { int l = A.length; int result = 0; int[ ] B = new int[32]; for(int i = 0; i < 32; i ++){ B[i] = 0; for(int j = 0; j < l; j ++){ if(((A[j] >> i) & 1) == 1){ B[i] += 1; } } B[i] %= 3; result |= B[i] << i ; } return result; } }
相关文章推荐
- 【LEETCODE OJ】Single Number II
- leedcode做题总结,题目Single NumberI/II 2013/10/01-02
- leetcode题目:Single Number和Single Number II
- LeetCode OJ平台上的Climbing Stairs题目用java迭代解决
- LeetCode OJ : Single Number II
- [LeetCode OJ] Single Number II
- 【LeetCode OJ】Single Number II
- LeetCode OJ--Single Number II **
- [LeetCode OJ]Single number II
- Single Number II——系列题目的翻译
- LeetCode OJ-- Single Number II **@
- LeetCode OJ平台上Maximum Subarray题目O(n)复杂度解决方式
- LeetCode OJ - Single Number II
- LeetCode OJ:Single NumberII
- LeetCode OJ——Single Number II
- 27.leetcode题目137: Single Number II(考察位操作)
- Single Number II
- LeetCode_Single Number II
- LeetCode-Single Number II
- Leetcode习题: SingleNumber II