1.在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
<?php
function Find($target, $array)
{
$row = count($array);
$col = count($array[0]);
$r = $row-1;
$c = 0;
while($r>=0 && $c<$col){
if($target > $array[$r][$c]){
$c++;
}else if($target < $array[$r][$c]){
$r--;
}else{
return true;
}
}
return false;
}
$arr2D = array(array(1,2,3),array(4,5,8),array(7,18,20));
foreach ($arr2D as $key => $value) {
print_r($value);
echo "</br>";
}
$num = 8;
echo Find($num,$arr2D);
Array ( [0] => 1 [1] => 2 [2] => 3 )
Array ( [0] => 4 [1] => 5 [2] => 8 )
Array ( [0] => 7 [1] => 18 [2] => 20 )
1
2.请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
<?php
function replaceSpace($str)
{
$L = strlen($str);
if($str == null || $L < 0){
return false;
}
$replaceNum = 0;
for($i = 0; $i < $L; $i++){
if($str[$i] == ' '){
$replaceNum++;
}
}
$newL = $L + ($replaceNum*2);
$pL = $L - 1;
$pNewL = $newL - 1;
while ($pL>=0 && $pNewL > $pL) {
if($str[$pL] == ' '){
$str[$pNewL--] = '0';
$str[$pNewL--] = '2';
$str[$pNewL--] = '%';
}else{
$str[$pNewL--] = $str[$pL];
}
$pL--;
}
return $str;
}
$str = 'We AreHappy';
echo replaceSpace($str);
We%20AreHappy
网友评论