算法 中等 | 38. 搜索二维矩阵 II

算法 中等 | 38. 搜索二维矩阵 II

题目描述

写出一个高效的算法来搜索m×n矩阵中的值,返回这个值出现的次数。

这个矩阵具有以下特性:

每行中的整数从左到右是排序的。
每一列的整数从上到下是排序的。
在每一行或每一列中没有重复的整数。

样例1

输入:
[[3,4]]
target=3
输出:1

样例2

输入:
    [
      [1, 3, 5, 7],
      [2, 4, 7, 8],
      [3, 5, 9, 10]
    ]
    target = 3
输出:2

java题解

从左下角开始,往右上角逼近

public class Solution {
    public int searchMatrix(int[][] matrix, int target) {
        // check corner case
        if (matrix == null || matrix.length == 0) {
            return 0;
        }
        if (matrix[0] == null || matrix[0].length == 0) {
            return 0;
        }
        
        // from bottom left to top right
        int n = matrix.length;
        int m = matrix[0].length;
        int x = n - 1;
        int y = 0;
        int count = 0;
        
        while (x >= 0 && y < m) {
            if (matrix[x][y] < target) {
                y++;
            } else if (matrix[x][y] > target) {
                x--;
            } else {
                count++;
                x--;
                y++;
            }
        }
        return count;
    }
}

C++题解

从左下角开始,往右上角逼近

class Solution {
public:
    int searchMatrix(vector<vector<int> > &matrix, int target) {
        // write your code here
        if (matrix.empty())
        {
            return 0;
        }
        int m = matrix.size();
        int n = matrix[0].size();
        int i = m - 1;
        int j = 0;
        int occur = 0;
        while (i >= 0 && j < n)
        {
            if (matrix[i][j] == target)
            {
                ++occur;
            }
            if (matrix[i][j] < target)
            {
                ++j;
            }
            else
            {
                --i;
            }
        }
        return occur;
    }
};

python题解

从左下角开始,往右上角逼近

class Solution:
    def searchMatrix(self, matrix, target):
        if matrix == [] or matrix[0] == []:
            return 0
            
        row, column = len(matrix), len(matrix[0])
        i, j = row - 1, 0
        count = 0
        while i >= 0 and j < column:
            if matrix[i][j] == target:
                count += 1
                i -= 1
                j += 1
            elif matrix[i][j] < target:
                j += 1
            elif matrix[i][j] > target:
                i -= 1
        return count
发布了202 篇原创文章 · 获赞 31 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_43233085/article/details/104112887