二維數組中的查找 (劍指Offer)

題目描述:在一個二維數組中(每個一維數組的長度相同),每一行都按照從左到右遞增的順序排序,每一列都按照從上到下遞增的順序排序。請完成一個函數,輸入這樣的一個二維數組和一個整數,判斷數組中是否含有該整數。

c++:


class Solution {
public:
    bool Find(int target, vector<vector<int> > array) {
        int rows = array.size();
        int cols = array[0].size();
        if(!array.empty() && rows > 0 && cols > 0){
            int row = 0;
            int col = cols - 1;
            while(row < rows && col >= 0){
                if(array[row][col] == target){
                    return true;
                }else if(array[row][col] > target){
                    --col;
                }else{
                    ++row;
                }
            }
        }
        return false;
    }
};

php

<?php
 
function Find($target, $array)
{
    // write code here
    if(is_null($array));
        $row = count($array);
        $col = count($array['0']);
         
        $i = 0;
        $j = $col;
        while(true)
        {
 
            if($array[$i][$j-1] == $target){
                return true;
            }
            if($array[$i][$j-1]>$target)
            {
                $j -= 1;
            }else if($array[$i][$j-1] < $target)
            {
                $i +=1 ;
            }
 
            if($i == $row || $j == 0)
                return false;
        }
 
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章