查找出現奇數次的數字的 PHP 程式
什麼是 PHP?
PHP(超文字預處理器)是一種廣泛使用的伺服器端指令碼語言,用於 Web 開發。它允許開發人員將程式碼嵌入 HTML 檔案中,從而建立動態網頁並與資料庫互動。PHP 以其簡單性、多功能性和與流行資料庫的廣泛整合能力而聞名。它提供了廣泛的擴充套件,並擁有龐大的開發者社群,確保了充足的資源和支援。
查找出現奇數次的數字的 PHP 程式
“出現奇數次的數字”的概念是指在陣列中查找出現奇數次的數字,而所有其他數字都出現偶數次。換句話說,陣列中只有一個數字的計數為奇數,而所有其他數字的計數為偶數。
示例
讓我們舉個例子來說明這個概念
考慮以下陣列:[2, 3, 4, 3, 1, 4, 2, 1, 1]
在這個陣列中,除了數字 1 之外,所有數字都出現了偶數次。數字 1 出現了 3 次,這是一個奇數計數。因此,數字 1 是在這個陣列中出現奇數次的數字。
此程式可以使用多種方法實現,例如雜湊、按位運算或排序。
方法 1 - 使用排序
<?php
function findOddNumber($arr) {
$count = array();
foreach($arr as $num) {
if(isset($count[$num])) {
$count[$num]++;
} else {
$count[$num] = 1;
}
}
foreach($count as $num => $occurrences) {
if($occurrences % 2 != 0) {
return $num;
}
}
return -1; // If no number occurs an odd number of times
}
// Example usage
$arr = array(5, 7, 2, 7, 5, 2, 1, 1, 9, 9, 9);
$oddNumber = findOddNumber($arr);
if($oddNumber != -1) {
echo "The number occurring an odd number of times is: " . $oddNumber;
} else {
echo "No number occurs an odd number of times in the array.";
}
?>
輸出
The number occurring an odd number of times is: 9
方法 2 - 使用雜湊
<?php
function findOddNumber($arr) {
$hash = array();
foreach($arr as $num) {
if(isset($hash[$num])) {
$hash[$num]++;
} else {
$hash[$num] = 1;
}
}
foreach($hash as $num => $occurrences) {
if($occurrences % 2 != 0) {
return $num;
}
}
return -1; // If no number occurs an odd number of times
}
// Example usage
$arr = array(2, 3, 4, 3, 1, 4, 2, 1, 1);
$oddNumber = findOddNumber($arr);
if($oddNumber != -1) {
echo "The number occurring an odd number of times is: " . $oddNumber;
} else {
echo "No number occurs an odd number of times in the array.";
}
?>
輸出
The number occurring an odd number of times is: 1
方法 3 - 使用按位異或運算。
<?php
function odd_occurrence($arr)
{
$result = 0;
# Traverse the array
foreach ($arr as &$value)
{
# Xor (exclusive or)
# Bits that are set in $a or $b but not both are set.
$result = $result ^ $value;
}
return $result;
}
$num1 = array( 3, 5, 6, 2, 3, 6, 2, 5, 7);
print_r(odd_occurrence($num1)."
");
?>
輸出
7
結論
總之,PHP 程式有效地識別了陣列中出現奇數次的數字。它為各種應用程式和演算法提供了可靠的解決方案。透過遍歷陣列並跟蹤每個數字的計數,程式準確地識別了計數為奇數的數字。
查找出現奇數次的數字的 PHP 程式是一種高效的解決方案,它利用了雜湊的概念。它接受一個輸入陣列,並使用雜湊表儲存每個數字的計數。透過遍歷雜湊表,它識別出計數為奇數的數字,表示陣列中出現奇數次的數字。使用雜湊技術,程式實現了 O(n) 的時間複雜度,其中 n 是輸入陣列的大小。這使得它成為在陣列中查找出現奇數次的數字的最佳解決方案,為各種應用程式和演算法提供了可靠的工具。
程式可以使用按位異或運算來查找出現奇數次的數字。透過對陣列中的所有元素執行異或運算,程式可以有效地提取唯一的數字。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP