LeetCode11|搜索二维矩阵

时间:2022-07-23
本文章向大家介绍LeetCode11|搜索二维矩阵,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1,问题简述

编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性:

每行中的整数从左到右按升序排列。

每行的第一个整数大于前一行的最后一个整数。

2,示例

输入:
matrix = [
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]
target = 3
输出: true

3,题解思路

可以采用两种方式来做,第一种暴力破解+HashSet来做,第二种方式是使用找规律的方式进行操作。

4,题解程序


import java.util.HashSet;

public class MatrixSearchTest {
    public static void main(String[] args) {
        int[][] matrix = {
                {1, 3, 5, 7},
                {10, 11, 16, 20},
                {23, 30, 34, 50}
        };
        int target = 3;
        boolean flag = searchMatrix(matrix, target);
        System.out.println("flag = " + flag);
        boolean flag2 = searchMatrix2(matrix, target);
        System.out.println("flag2 = " + flag2);
    }

    public static  boolean searchMatrix2(int[][] matrix, int target) {

        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return false;
        }
        int row = 0;
        int col = matrix[0].length-1;
        while (row < matrix.length && col >= 0) {
            if (matrix[row][col] == target) {
                return true;
            } else if (matrix[row][col] < target) {
                row++;
            } else {
                col--;
            }
        }
        return false;
    }

    public static boolean searchMatrix(int[][] matrix, int target) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return false;
        }
        int rowLength = matrix.length;
        int colLength = matrix[0].length;
        HashSet<Integer> hashSet = new HashSet<>(rowLength * colLength);
        for (int[] ints : matrix) {
            for (int j = 0; j < colLength; j++) {
                hashSet.add(ints[j]);
            }
        }
        return hashSet.contains(target);
    }
}

5,总结,现在的每道题基本上数据集合用的都不一样,HashMap,List,Array等,这里就采用了HashSet集合进行数据的查找。