《leetcode-php》获取数组中只出现一次的数字,其他的出现2次

Given an array of integers, every element appears twice 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)。

<?php
function singleNumber($array) {
    $once  = 0;
    foreach ($array as $value) {
        $once  ^= $value;
    }
    return $once;
}
$array = array(10,3,4,5,6,3,5,6,4);
$ret   = singleNumber($array);
print $ret;

猜你喜欢

转载自blog.csdn.net/less_cold/article/details/88013270
今日推荐