[LeetCode] Single Number II
2014-06-27 23:21
260 查看
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?
方法一:创建一个长度为 多少个bit/sizeof(int) * 8的数组 count[sizeof(int)*8],count[i] 表示在在 i 位
出现的 1 的次数。如果 count[i] 是 3 的整数倍,则忽略;否则就把该位取出来组成答案。
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
方法一:创建一个长度为 多少个bit/sizeof(int) * 8的数组 count[sizeof(int)*8],count[i] 表示在在 i 位
出现的 1 的次数。如果 count[i] 是 3 的整数倍,则忽略;否则就把该位取出来组成答案。
class Solution { public: int singleNumber(int A[], int n) { vector<int> cnt; int width = sizeof(int)*8; cnt.resize(width, 0); int res = 0; for(int i = 0; i< n; i++) { for(int j = 0; j< width; j++) { cnt[j] += (A[i] >> j) & 0x1; //cnt[j] %= 3; } } for(int j = 0; j< width; j++) { //cout << "j :\t" <<j <<"\t cnt\t"<< cnt[j]<<endl; if(cnt[j]%3 != 0) res ^= ( 1 << j); } return res; } } ;
相关文章推荐
- [LeetCode] - Single Number II
- LeetCode Single Number, Single Number II
- leetcode136:single number I&II 及拓展
- leetcode Single Number I II III
- leetcode -- Single Number II
- LeetCode | Single Number II
- LeetCode: Single Number II
- LeetCode-Single Number II
- [leetcode]Single Number II
- LeetCode:Single NumberII
- (复习)[LeetCode]Single Number II
- Leetcode Single Number II
- Leetcode Single Number II
- leetcode 之 Single Number II
- leetcode(137)数组之Single Number II
- Leetcode Single Number II (面试题推荐)
- Leetcode之SingleNumber I/II/III
- 【leetcode刷题笔记】Single Number II
- Leetcode--Single Number II
- leetcode 虐我篇之(十)Single Number II