lintcode 落单的数 II
2017-09-16 12:26
246 查看
落单的数 II
描述笔记
数据
评测
给出3*n + 1 个的数字,除其中一个数字之外其他每个数字均出现三次,找到这个数字。
您在真实的面试中是否遇到过这个题?
Yes
样例
给出 [1,1,2,3,3,3,2,2,4,1] ,返回 4
挑战
一次遍历,常数级的额外空间复杂度
标签
贪心
相关题目
思路:和上一道题一样,还是用位操作,尝试消掉出现3次的数字。
对int的32bit的各个位中1出现的次数进行统计,再对数组中所有元素的逐个进行统计,然后对每个bit对3取余,最终的结果就是只出现一次的数字值,再相加就是只出现过一次的数
class Solution { public: /* * @param A: An integer array * @return: An integer */ int singleNumberII(vector<int> &A) { // write your code here int end=0; for(int i=0;i<32;i++) { int num=0;//每位1出现次数 for(auto n:A) { if(findzero(n,i)) num++; } end+=((num%3)<<i);//再左移恢复原值 } return end; } bool findzero(int i,int k) { if((i>>k)&1)//先右移判断 return true; else return false; } };
相关文章推荐
- Lintcode 落单的数 II
- lintcode,落单的数 II
- Lintcode落单的数 删除排序数组中的重复数字 II
- LintCode-落单的数 II
- LintCode 落单的数 II
- lintcode 中等题:Singleton number II 落单的数 II
- 落单的数 II-LintCode
- ***[Lintcode]Single Number II 落单的数 II
- lintcode-83-落单的数 II
- 三数之和 II——LintCode
- Calculate Maximum Value II -LintCode
- python_lintcode_47主元素_47主元素 II_48主元素 III
- lintcode,删除排序链表中的重复数字 II
- Lintcode: Interval Sum II
- python - LintCode 4. 丑数 II
- LintCode:46. 主元素I VS 47. 主元素 II VS 48. 主元素 III
- LintCode-k数和 II
- LintCode-二叉树的层次遍历 II
- lintcode: 跳跃游戏 II
- lintcode-medium-Single Number II