当前位置:网站首页>Sword finger offer 04 Find in 2D array

Sword finger offer 04 Find in 2D array

2022-06-25 15:36:00 anieoo

Original link : The finger of the sword Offer 04. Search in a two-dimensional array

 

solution:

        Violent simulation , Time complexity O(m * n)

class Solution {
public:
    bool findNumberIn2DArray(vector<vector<int>>& matrix, int target) {
        for(auto &x : matrix)
            for(auto &y : x) {
                if(y == target) return true;
            }
        return false;
    }
};

        Time complexity of binary search line by line O(nlogn)

class Solution {
public:
    bool findNumberIn2DArray(vector<vector<int>>& matrix, int target) {
        int n = matrix.size();
        if (matrix.size() == 0 || matrix[0].size() == 0)
            return false;
        for(int i = 0;i < n;i++) {
            if(binSearch(matrix[i], target)) return true;
        }
        return false;
    }

    bool binSearch(vector<int> &nums, int target) {
        int l = 0,r = nums.size() - 1;
        while(l < r) {
            int mid = l + (r - l) / 2;
            if(nums[mid] >= target) r = mid;
            else l = mid + 1;
        }
        if(nums[l] == target) return true;
        return false;
    }
};

Start at the top right , If matrix[x][y] > target,y++,else x--

class Solution {
public:
    bool findNumberIn2DArray(vector<vector<int>>& matrix, int target) {
        if(matrix.size() == 0 || matrix[0].size() == 0) return false;
        int n = matrix.size(),m = matrix[0].size();
        int x = n - 1,y = 0;
        while(x >= 0 && y < m) {
            if(matrix[x][y] == target) return true;
            if(matrix[x][y] < target) y++;
            else x--;
        }                
        return false;
    }
};

 

原网站

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