class TitleThree
{
private $nums;
private $count;
public function __construct($nums, $count = 1)
{
if (!is_array($nums)) {
throw new InvalidArgumentException('第一个参数必须是数组');
}
if (!is_numeric($count)) {
throw new InvalidArgumentException('第二个参数必须是数字');
}
$this->nums = $nums;
$this->count = $count;
}
/**
* 方法一:使用数组函数统计元素出现的次数
* @return string
*/
public function findSingleNumber1()
{
$count = array_count_values($this->nums);
$filtered = array_filter($count, function($freq) {
return $freq === $this->count;
});
return implode(',', array_keys($filtered));
}
/**
* 方法二:手动循环统计
* @return string
*/
public function findSingleNumber2()
{
$exist = [];
$ignore = [];
foreach ($this->nums as $num) {
if (in_array($num, $ignore)) {
continue;
}
if (!isset($exist[$num])) {
$exist[$num] = 0;
}
$exist[$num]++;
if ($exist[$num] > $this->count) {
$ignore[] = $num;
unset($exist[$num]);
}
}
$res = [];
foreach ($exist as $num => $freq) {
if ($freq === $this->count) {
$res[] = $num;
}
}
return implode(',', $res);
}
/**
* 方法三:排序后统计
* @return string
*/
public function findSingleNumber3()
{
sort($this->nums);
$len = count($this->nums);
$res = [];
$currentCount = 1;
for ($i = 1; $i < $len; $i++) {
if ($this->nums[$i] === $this->nums[$i - 1]) {
$currentCount++;
} else {
if ($currentCount === $this->count) {
$res[] = $this->nums[$i - 1];
}
$currentCount = 1;
}
}
if ($currentCount === $this->count) {
$res[] = $this->nums[$len - 1];
}
return implode(',', $res);
}
}
try {
$count = 1;
$index = new TitleThree([2, 2, 1], $count);
$res1 = $index->findSingleNumber1();
echo "方法一出现 $count 次的数字结果:";
var_dump($res1);
$res2 = $index->findSingleNumber2();
echo "方法二出现 $count 次的数字结果:";
var_dump($res2);
$res3 = $index->findSingleNumber3();
echo "方法三出现 $count 次的数字结果:";
var_dump($res3);
} catch (InvalidArgumentException $e) {
echo "错误:".$e->getMessage();
}
方法一出现 1 次的数字结果:string(25) “23,45,54,22,9,5,654,66,67”
方法二出现 1 次的数字结果:string(25) “23,45,54,22,9,5,654,66,67”
方法三出现 1 次的数字结果:string(25) “5,9,22,23,45,54,66,67,654”
评 论