我刚刚为PHP解决了这些问题并且遇到了其中一个问题.问题是:
You have a PHP 1 dimensional array. Please write a PHP function that
takes 1 array as its parameter and returns an array. The function must
delete values in the input array that shows up 3 times or more?For example, if you give the function
array(1, 3, 5, 2, 6, 6, 6, 3, 1, 9)
the function will return
array(1, 3, 5, 2, 3, 1, 9)
我能够检查它们是否在重复,但我将它应用于我得到的数组作为输入.
function removeDuplicate($array){
$result = array_count_values( $array );
$values = implode(" ", array_values($result));
echo $values . "<br>";
}
$qArray = array(1, 3, 5, 2, 6, 6, 6, 3, 1, 9);
removeDuplicate($qArray);
还有一件事,我们不能使用array_unique,因为它包含重复的值,并且我们将它们从当前数组中完全删除.
解决方法:
假设该值可能不会在数组中的任何位置出现3次:
$array = array(1, 3, 5, 2, 6, 6, 6, 3, 1, 9);
// create array indexed by the numbers to remove
$remove = array_filter(array_count_values($array), function($value) {
return $value >= 3;
});
// filter the original array
$results = array_values(array_filter($array, function($value) use ($remove) {
return !array_key_exists($value, $remove);
}));
如果值可能不会连续出现3次:
$results = [];
for ($i = 0, $n = count($array); $i != $n;) {
$p = $i++;
// find repeated characters
while ($i != $n && $array[$p] === $array[$i]) {
++$i;
}
if ($i - $p < 3) {
// add to results
$results += array_fill(count($results), $i - $p, $array[$p]);
}
}