[leetcode]Single Number II
2014-04-02 21:03
253 查看
Single Number II
My SubmissionsGiven 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?
Have you been asked this question in an interview?
题目:除了一个元素以外其它元素出现3次,而只有一个元素出现一次
思路:将每个元素转化成二进制并将其对应的bit位置1,所以出过三次的元素对应的位应该是3的倍数,而最后只会剩下那只出现一次元素所对应的二进制位。
int singleNumber(int a[], int n) { int bitCount[32] = {0}; for(int i = 0; i < n; i++){ int bit = 1; for(int j = 0; j < 32; j++){ if(bit & a[i]){ bitCount[j] = (bitCount[j] + 1) % 3; } bit <<= 1; } } int retNum = 0; for(int i = 0; i < 32; i++){ retNum = retNum * 2 + bitCount[31 - i]; } return retNum; }
如果对其进一步可作扩展,除一个元素出现2次其它都出现3次,也可以用此方法。
如一个元素出现两次,一个出现1次,其它出现4次。也可以
相关文章推荐
- reader and writer
- 强引用 弱引用 软引用 虚引用
- Java反射实现DWR技术级联查询框的封装
- 一步步学习微软InfoPath2010和SP2010--第十一章节--创建批准流程(4)--审批域
- 入职快盘
- hibernate sqlite jdbctemplate 待研究
- 在Mybatis3开发中与配置相关的7点体会
- 黑马程序员 _7 OC基础 继承、多态、分类
- [LeetCode] Single Number II
- c语言程序设计
- fedora 安装chrome
- 【数学】欧拉函数和相关结论
- 简单的ajax登陆验证
- C++ 常量区 堆区 栈区
- linux系统之编译内核实现iptables应用层过滤
- There will be decreasing performance of oracle by delete whole table and then insert ...
- DICOM中几个判断图像方向的tag
- php中urlencode与rawurlencode的区别
- ffmpeg使用
- HDU 2896 病毒侵袭