一个菜鸟驿站!

php面试题(二)(来自于面试~)

PHP 2021-05-07 浏览(1917) 评论(0)
- N +

文章目录 [+]

第五家

1.变量$a, $b, $c随机true或者false,请在$a为true,并且$b或$c有一个为true情况下输出”hello world” 

$a = random_int(0, 1);
$b = random_int(0, 1);
$c = random_int(0, 1);

if($a && ($b || $c)){
    echo 'hello world!';
}

2."S-3341"、"UX331"、"KL^72T"如何求其中数字之和,(3341+331+72) 。(绝非最佳方案,可以评论处留言)

$str1 = 'S-3341';
$str2 = 'UX331';
$str3 = 'KL^72T';
 
preg_match_all("/(\d+\.?\d+)/", $str1, $num1);
preg_match_all("/(\d+\.?\d+)/", $str2, $num2);
preg_match_all("/(\d+\.?\d+)/", $str3, $num3);
 
$num1 = $num1[1][0] ?? 0;
$num2 = $num2[1][0] ?? 0;
$num3 = $num3[1][0] ?? 0;
echo $num1 + $num2 + $num3;

3.修改下面数组$arr中键“value”的值,让其值等于原来值的平方(例如:11.2变成11.2x11.2)。(绝非最佳方案,可以评论处留言)

$arr = [
    [
        'id'  => 1,
        'sub' => [
            [
                'value' => 11.2
            ],
            [
                'value' => 34.5
            ]
        ]
    ],
    [
        'id'  => 2,
        'sub' => [
            [
                'value' => 25.2
            ],
            [
                'value' => 39.1
            ],
            [
                'value' => 32.1
            ]
        ]
    ],
];

//复杂度O(n^2)
foreach ($arr as $k => $v) {
    foreach ($v['sub'] as $kk => $vv) {
        $arr[$k]['sub'][$kk] = $vv['value'] * $vv['value'];
    }
}

4.算法题

Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.

For example, given nums = [0, 1, 0, 42 ,3], after calling your function, nums should be [1, 42, 3, 0, 0].

Note:

You must do this in-place without making a copy of the array.

Minimize the total number of operations

<?php
//解法1,记录非0数量
$arr =  [0, 1, 0, 42 ,3];
$len = count($arr);
$j = 0;//记录不是0的个数
for ($i = 0; $i < $len; $i++) {
    //不是0的话,就给他挪动
    if ($arr[$i] != 0) {
        $temp = $arr[$j];
        $arr[$j] = $arr[$i];//第几个位置变为非0的,
        $arr[$i] = $temp;
        $j++;
    }
}
echo '<pre>';
print_r($arr);
die;

//解法2,记录0数量
$num = [0,1,0,42,3];
$len = count($num);
$j = 0;
for ($i = 0; $i < $len; $i++) {
    if ($num[$i] == 0) {
        $j++;
    }else{
        $temp = $num[$i - $j];
        $num[$i - $j] = $num[$i];
        $num[$i] = $temp;
    }
}

//解法3,同解法1,是解法1的拆开的解法
$arr =  [0, 1, 0, 42 ,3];
$len = count($arr);
$j = 0;//记录不是0的个数
for ($i = 0; $i < $len; $i++) {
    //不是0的话,就给他挪动
    if ($arr[$i] != 0) {
        $arr[$j] = $arr[$i];
        $j++;
    }
}
for ($i = $j; $i < $len; $i++) {
    $arr[$i] = 0;
}
echo '<pre>';
print_r($arr);
die;


5.


标签:
作者:猫巷

,

评论列表 (0)条评论

发表评论

召唤伊斯特瓦尔