本文實(shí)例講述了PHP實(shí)現(xiàn)二維數(shù)組中的查找算法。分享給大家供大家參考,具體如下:
方法1:silu從左下角最后一行的第一個(gè)元素開始,遍歷。如果小于target 則遍歷該行的所有元素,找到結(jié)束。如果大于繼續(xù)往上一行進(jìn)行。等于直接結(jié)束。
<?php function Find($target, $array) { $m_y = count($array['0']); $m_x = count($array); for($i=$m_x-1;$i>=0;$i--){ if($array[$i]['0'] < $target){ for($j=1;$j<$m_y;$j++){ if($array[$i][$j] == $target){ return 1; break; } } } if($array[$i]['0'] == $target){ return 1; break; } } }
方法2:
function Find($target, $array) { $m_y = count($array['0']); $m_x = count($array); $i = 0; for($i =$m_x-1,$j=0;$i>=0&&$j<$m_y;){ if($array[$i][$j]<$target){ $j++; continue; } if($array[$i][$j]>$target){ $i--; continue; } if($array[$i][$j] == $target){ return 1; } } }
方法3:
function Find($target, $array) { $m_y = count($array['0']); $m_x = count($array); $i = $m_x-1; $j = 0; while(1){ if($array[$i][$j]<$target){ $j++; } if($array[$i][$j]>$target){ $i--; } if($array[$i][$j] == $target){ return 1; } if($i == 0||$j == $m_y-1){ return 0; } } }
希望本文所述對大家PHP程序設(shè)計(jì)有所幫助。