[LeetCode] Single Number II, Solution
2016-01-12 11:11
239 查看
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?
[Thoughts]
这个题有类似于single number的解法,即通过位运算,一遍扫描得到结果。还是读书的时候见过,大概是两个变量,相互做异或、补之类的运算,早不记得详情了。
现在的解法是比较普通的。因为题目已经说了,除了一个数字以外,其他的都出现了3次,如果我们把那个特殊的数剔除,并把剩下的数于每一位来加和的话,每一位上1出现的次数必然都是3的倍数。所以,解法就在这里,将每一位数字分解到32个bit上,统计每一个bit上1出现的次数。最后对于每一个bit上1出现的个数对3取模,剩下的就是结果。
[code] 1 int singleNumber(int A[], int n) { 2 vector<int> bit(32,0); 3 4 for(int i =0; i< n; ++i) 5 { 6 int k=1; 7 for(int j =0; j<32; ++j) 8 { 9 int rotated; 10 if((rotated = A[i]>>j) == 0) break; 11 bit[j] += rotated & k; 12 } 13 } 14 15 int target=0; 16 for(int i =0; i<32; ++i) 17 { 18 target += (bit[i]%3 <<i); 19 } 20 return target; 21 }
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
[Thoughts]
这个题有类似于single number的解法,即通过位运算,一遍扫描得到结果。还是读书的时候见过,大概是两个变量,相互做异或、补之类的运算,早不记得详情了。
现在的解法是比较普通的。因为题目已经说了,除了一个数字以外,其他的都出现了3次,如果我们把那个特殊的数剔除,并把剩下的数于每一位来加和的话,每一位上1出现的次数必然都是3的倍数。所以,解法就在这里,将每一位数字分解到32个bit上,统计每一个bit上1出现的次数。最后对于每一个bit上1出现的个数对3取模,剩下的就是结果。
[code] 1 int singleNumber(int A[], int n) { 2 vector<int> bit(32,0); 3 4 for(int i =0; i< n; ++i) 5 { 6 int k=1; 7 for(int j =0; j<32; ++j) 8 { 9 int rotated; 10 if((rotated = A[i]>>j) == 0) break; 11 bit[j] += rotated & k; 12 } 13 } 14 15 int target=0; 16 for(int i =0; i<32; ++i) 17 { 18 target += (bit[i]%3 <<i); 19 } 20 return target; 21 }
相关文章推荐
- [LeetCode] Copy List with Random Pointer, Solution
- 生成词云图
- iOS--搜索UISearchController&&UISearchDisplayController
- [转]日常沟通之如何处理异议
- 《FPGA全程进阶---实战演练》第九章 计数器要注意
- iOS 百思不得姐 项目
- gizp网站压缩
- 读数据库所有表和表结构的sql语句了(mssql)
- 基于jq 滚动条到底加载更多的方法
- git查看本地和创建分支、上传分支、提交代码到分支、删除分支等,git分支
- mysql 索引
- [LeetCode] Combination Sum II, Solution
- [LeetCode] Combinations, Solution
- [LeetCode] Construct Binary Tree from Preorder and Inorder Traversal, Solution
- [LeetCode] Container With Most Water, Solution
- [LeetCode] Convert Sorted List to Binary Search Tree, Solution
- [LeetCode] Count and Say, Solution
- [LeetCode] Decode Ways, Solution
- [FaceBook] Hanoi Moves, Solution
- [Facebook] Products of all elements