Single Number II
2016-01-05 10:05
423 查看
题目
Given an array of integers, every element appears three timesexcept for one.Find that single one.
其他出现3次,找出唯一出现1次的
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
思路(别人的)
原地址I'll try to explain ziyihao solution since the first answer is not accurately explained. The main idea of ziyihao's solution is coming from course digital logic. That is, we have a initial state(x, y), and a target state(z), the goal is to find out the binary
operations(z=f(x, y)):
The solution use two bit (a,b) to represent the initial state:
00: appear 3n times
01: appear 3n+1 times
10: appear 3n+2 times
The target state can be easily deducted that we want:
if data incoming: 00 -> 01 ->10 -> 00 if no data incoming, no change.
As a result, we can calculate the table in ziyihao's post:
current incoming next a b c a b 0 0 0 0 0 0 1 0 0 1 1 0 0 1 0 0 0 1 0 1 0 1 1 1 0 1 0 1 0 0
The next step is to calculate the binary operations we need from this state table, which is actually a general technique used in digital circuit course. Let's look at bit "a" first:
current incoming next a b c a 0 0 0 0 0 1 0 0 1 0 0 1 0 0 1 0 0 1 1 1 1 0 1 0
As mentioned in ziyihao's post, we only need care about the rows has value "1" in "next " column, that is row 3 and row 5.
So we can get:
a=a&~b&~c + ~a&b&c
Use the same technique and we can get the binary operations for b.
代码
int singleNumber(int* nums, int numsSize) { int a=0; int b=0; int c; int i; //we need to implement a tree-time counter(base 3) that if a bit appears three time ,it will be zero. //#curent income ouput //# ab c/c ab/ab //# 00 1/0 01/00 //# 01 1/0 10/01 //# 10 1/0 00/10 // a=~abc+a~b~c; // b=~a~bc+~ab~c; for(i=0;i<numsSize;i++) { c = nums[i]; int tmp = (~a&b&c)|(a&~b&~c); b = (~a&~b&c)|(~a&b&~c); a = tmp; } // //we need find the number that is 01,10 => 1, 00 => 0. return a|b; }
最重要的是推出那个公式!!!
int tmp = (~a&b&c)|(a&~b&~c); b = (~a&~b&c)|(~a&b&~c); a = tmp;设置tmp变量是因为,计算b的时候需要的a是上一状态,而不是当前状态
相关文章推荐
- 嵌入式系统中看门狗的使用总结
- php中正则表达式基本语法
- WINDOW 安装pear
- 零基础学习hadoop到上手工作线路指导(编程篇)
- iOS开发之字符串中提取数字
- 关于a.b和a[b]的区别
- Maven的安装、配置及使用入门
- Linux系统维护监控工具集sysstat详解
- nginx rewrite规则
- Android中使用Streams的两种方法
- NSTimer导致的内存泄露,找了好久的问题
- 用readn与written实现解决粘包问题
- Linux/error.h中的错误对应(include/asm-generic/(errno.h)、(errno-base.h))
- Tomcat7+redis 实现session共享
- linux下IPTABLES配置详解(转)
- share my tools With Xcode
- http cookie
- java中二进制和流的相互转换
- android 常用到的shape属性(填充与描边)
- Linux服务器性能数据收集【sar、pidstat、iostat、mpstat、sadf、sadc】