题意:
解题思路:
思路:
1. 异或操作,两个相同的数异或结果为0;
2. 一个数跟0异或是这个数本身。
PHP代码实现:
class Solution {
/**
* @param Integer[] $nums
* @return Integer
*/
function singleNumber($nums) {
$res = $nums[0];
for ($i = 1; $i < count($nums); $i++) {
$res ^= $nums[$i];
}
return $res;
}
function singleNumber1($nums) {
$arr = [];
foreach($nums as $value) {
if (!isset($arr[$value])) {
$arr[$value] = 1;
} else {
$arr[$value]++;
}
}
foreach ($arr as $key => $v) {
if ($v == 1) return $key;
}
}
function singleNumber2($nums) {
$arr = [];
foreach ($nums as $value) {
if (!isset($arr[$value])) {
$arr[$value] = 1;
} else {
unset($arr[$value]);
}
}
foreach($arr as $key => $v) {
return $key;
}
}
}
GO代码实现:
func singleNumber(nums []int) int {
res := 0
for _, v := range nums {
res ^= v
}
return res
}