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?
给出一个整数数组,除了一个出现一次的元素外,每个元素出现三次。找到只出现一次的元素。时间复杂度为O(n),空间复杂度为O(1)。
$twice是在数字出现第二次的时候把它记录下来。$once在第一次和第三次的时候把数字记录下来。
在数字出现第一次的时候,once有该数,twice没有,third没有
在数字出现第二次的时候,once没有该数,twice有,third没有
在数字出现第三次的时候,once有,twice有,third有。
^异或运算可以保证once在奇数次出现的时候有该数字。
&与运算保证确定第二次出现的时候,|或运算把该数字记录到twice中。
~取返运算加上&与运算,可以把该数字抵消掉。
<?php
function singleNumber($array) {
$twice = 0;
$once = 0;
foreach ($array as $value) {
//首先判断是否出现2次,出现多次是在once里面出现了的才算
$twice |= $once & $value;
//是否出现一次
$once ^= $value;
//是否出现三次
$third = $twice & $once;
//去掉出现3次的数
$twice &= ~$third;
$once &= ~$third;
}
return $once;
}
$array = array(10,3,4,5,6,3,3,5,5,6,6,4,4);
$ret = singleNumber($array);
print $ret;