当前位置:网站首页>Given a two-dimensional list of m*n, find out whether a number exists

Given a two-dimensional list of m*n, find out whether a number exists

2022-06-21 08:19:00 liuliang514218119

<?php
#  Given a m*n 2-D list of , Find out if a number exists , The list has the following features :
#  The list of each row is sorted from left to right 
#  The first number of each line is larger than the last number of the previous line 
# [
# [1,3,5,7],
# [10,11,16,20],
# [23,30,34,50],
# ]
# [
# [0,1,2,3],
# [4,5,6,7],
# [8,9,10,11],
# ...
# ]

function matrix_search($matrix, $target)
{
    
    $height = count($matrix); //  That's ok 
    if ($height < 1) {
    
        return false;
    }
    $width = count($matrix[0]); //  Column 
    if ($width < 1) {
    
        return false;
    }
    $left = 0;
    $right = $width * $height - 1;
    while ($left <= $right) {
    
        $mid = intval(($left + $right) / 2);
        $row = intval($mid / $width); //  Divide by the width   Key in the first few lines 
        $col = $mid % $width; //  Width remainder   In which column are the keys 
        if ($matrix[$row][$col] == $target) {
    
            return true;
        } else if ($matrix[$row][$col] > $target) {
    
            $right = $mid - 1;
        } else {
    
            $left = $mid + 1;
        }
    }
    return false;
}

$matrix = [
    [1, 3, 5, 7],
    [10, 11, 16, 20],
    [23, 30, 34, 50],
];
$target = 2;
var_dump(matrix_search($matrix, $target));

$target = 16;
var_dump(matrix_search($matrix, $target));
echo "\n";

原网站

版权声明
本文为[liuliang514218119]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/172/202206210812142472.html