Leetcode在线编程 single-number-ii
题目链接
题目描述
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?
题意
给定一个数组,数组里面所有数都是出现3次,只有唯一一个出现过一次,找出这个唯一点。
解题思路
神奇的位运算,可参考入门版的single-number
有挺多种解法,下面我先讲一种比较抽象的
先设定2个变量,one,two。one记录出现一次的那个数,two则保存出现二次以上的那些数
先看第一句 one = (one ^ A[i])&~two;
one异或A[i]则把one中A[i]删除,因为a^a=0:
two这代表着数上出现2次以上的数 ,取~之后,就变成只出现一次的数了
这样过滤掉出现2次以上的数据
接下来two= (two ^ A[i])&~one;
two删除A[i]中有的项,在与~one意思是,除去那些只出现一次的数
这样就可以保证one中最后存的是那个唯一出现一次的数
AC代码
class Solution {
public:
int singleNumber(int A[], int n) {
int one =0, two=0;
for(int i = 0 ; i < n ; i++)
{
one = (one ^ A[i])&~two;
two= (two ^ A[i])&~one;
}
return one;
}
};