关于这个问题,我已经用其他语言得到了很多答案,但是我想用php语言来回答。如果有人帮我,这是我的数组
$array = [1, 2, 3, 4, 4, 1, 2, 5, 5, 11, 11];发布于 2017-09-25 06:48:09
使用值()如下所示:
<?php
$array = [1, 2, 3, 4, 4, 1, 2, 5, 5, 11, 11];
$array_count_values = array_count_values($array);// get how many times a value appreas inside array
foreach($array_count_values as $key=>$val){ // now iterate over this newly created array
if($val ==1){ // if count is 1
echo $key. " in array come only one time.\n"; // this means value appears only one time inside array
}
}输出:- https://eval.in/867433或https://eval.in/867434
如果您想要数组中的值:-:-
<?php
$array = [1, 2, 3, 4, 4, 1, 2, 5, 5, 11, 11,13]; // increased one value to show you the output
$array_count_values = array_count_values($array);
$single_time_comming_values_array = [];
foreach($array_count_values as $key=>$val){
if($val ==1){
$single_time_comming_values_array[] = $key;
}
}
print_r($single_time_comming_values_array);发布于 2017-09-25 06:49:37
在这里,你可以用这样的东西-
<?php
function appearedOnce($arr)
{
$result = 0;
for($i=0; $i<sizeof($arr); $i++)
{
$result = $result ^ $arr[$i];
}
return $result;
}
$num = array(1, 2, 3, 4, 4, 1, 2, 5, 5, 11, 11);
print_r(appearedOnce($num)."\n")
?>发布于 2017-09-25 08:35:11
我最初的反应是采取一种更加步行的方式,正如您可能从这个示例中注意到的那样。然后我偶然发现了一个相关的讨论。
另一种方法是对数组进行排序,然后检查数字对是否重复。以下代码是将OP的数组与我可能将Michael Martin的C源代码转换为PHP的结果,如下所示:
<?php
$arr = [1, 2, 3, 4, 4, 1, 2, 5, 5, 11, 11];
sort($arr);
for($i = 0, $max = count($arr); $i < $max; $i++){
// is single number last element in array?
if($i == count($arr)-1)
$singleNum = $arr[$i];
// If adjacent elements the same, skip
if($i < count($arr)-1 && $arr[$i] == $arr[$i+1]){
$i++;
}
else
{
// found single number.
$singleNum = $arr[$i];
}
}
var_dump($singleNum);请参阅活码
https://stackoverflow.com/questions/46399038
复制相似问题