2014.1.13 20:25
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?
Solution:
Still, exclusive OR is a wonderful operator.
This time every number appears 3 times except an extra number. That is to say, every '1' bit appears 3k times if that extra number has '0' on this bit, or 3k+1 times if it has '1' on this bit. If we can use this 3k property, we can separate that extra number from those triads.
Here we define four variables:
a1: the bits that have appeared 3k+1 times.
a2: the bits that have appeared 3k+2 times.
b: the bits that have (or have not) appeared 3k times.
The algorithm works in the following process:
1. initialize all to 0.
2. for each A[i], update a2 from a1 and A[i].
3. for each A[i], update a1 from A[i].
4. for each A[i], update b from a1 and a2.
5. if a bit appears 3k times, it can't appear 3k+1 or 3k+2 time, thus subtract b from a1 and a2.
Time complexity is O(n), space complexity is O(1).
Accepted code:
1 // 1CE, 1AC, just try to avoid spelling error, OK? 2 class Solution { 3 public: 4 int singleNumber(int A[], int n) { 5 // IMPORTANT: Please reset any member data you declared, as 6 // the same Solution instance will be reused for each test case. 7 if(n <= 0){ 8 return 0; 9 } 10 11 int i; 12 int a1, a2; 13 int b; 14 15 a1 = a2 = b = 0; 16 for(i = 0; i < n; ++i){ 17 // notice: not a2 = (a1 & A[i]); 18 // 1CE here, not a[], but A[] 19 a2 |= (a1 & A[i]); 20 a1 = (a1 ^ A[i]); 21 b = ~(a1 & a2); 22 a1 &= b; 23 a2 &= b; 24 } 25 // all bits of '1' appear for 3k + 1 or 3k times, thus the remaining one is the result. 26 return a1; 27 } 28 };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)