当前位置:网站首页>给定一个m*n的二维列表,查找一个数是否存在

给定一个m*n的二维列表,查找一个数是否存在

2022-06-21 08:12:00 liuliang514218119

<?php
# 给定一个m*n的二维列表,查找一个数是否存在,列表有下列特性:
# 每一行的列表从左到右已经排序好
# 每一行第一个数比上一行最后一个数大
# [
# [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); // 行
    if ($height < 1) {
    
        return false;
    }
    $width = count($matrix[0]); // 列
    if ($width < 1) {
    
        return false;
    }
    $left = 0;
    $right = $width * $height - 1;
    while ($left <= $right) {
    
        $mid = intval(($left + $right) / 2);
        $row = intval($mid / $width); // 除以宽度 键在第几行
        $col = $mid % $width; // 宽度取余 键在第几列
        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://blog.csdn.net/liuliang514218119/article/details/125366302