标签:
下面是PHP的代码实现。
// array(1,2,3,2,5,69,8,2,5,2)
// array(1,2,5,8,5,5,5,98,65,5,5)
// array(1,2,6,8,6,6,6,98,65,6,6)
echo majority(array(2,2,3,2,2,68,8,2,5,2));
function majority($n) {
print_r($n);echo "<br />";
$elem = 0;
$count = 0;
// echo count($n);echo "<br />";
for($i = 0; $i<count($n); $i++) {
if($count == 0) {
$elem = $n[$i];
// print_r($elem);echo "<br />";
$count = 1;
}else{
// print_r($n[$i]);echo "<br />";
if($n[$i] == $elem) {
$count++;
}else{
$count--;
}
}
}
if($count>0)
<span style="white-space:pre"> </span>return $elem;
<span style="white-space:pre"> </span>else
<span style="white-space:pre"> </span>return "Don't have majority element<br />";
}
标签:
原文地址:http://blog.csdn.net/wide288/article/details/43192779