0%

二维数组中的查找


题目:

题解:

1、二分查找

  • 解题思路:将每一行进行二分查找。

  • 复杂度分析:

    • 时间复杂度O(mlogn):m为行数,n为列数
    • 空间复杂度O(1)
  • 代码:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    // 二分查找时间复杂度O(mlogn)
    class Solution {
    public boolean findNumberIn2DArray(int[][] matrix, int target) {

    if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
    return false;
    }
    // 获取行数
    int col = matrix.length;
    // 获取列数
    int row = matrix[0].length;

    for (int i = 0; i < col; i++) {
    int Left = 0;
    // 一行的长度matrix[0].length(有几列)
    int Right = row - 1;

    while (Left < Right ) {
    int mid = Left + (Right - Left) / 2;
    if (target > matrix[i][mid]) {
    Left = mid + 1;
    }else if (target < matrix[i][mid]) {
    Right = mid - 1;
    }else {
    return true;
    }
    }if (Left == Right) {
    System.out.println(matrix[i][Right]);
    if (matrix[i][Right] == target) {
    return true;
    }
    }
    }
    return false;
    }
    }

2、标志数法

  • 解题思路:

    • “根节点” 对应的是矩阵的 “左下角” 和 “右上角” 元素,本文称之为 标志数 ,以 matrix 中的 左下角元素 为标志数 flag ,则有:

      • 若 flag > target ,则 target 一定在 flag 所在 行的上方 ,即 flag 所在行可被消去。
      • 若 flag < target ,则 target 一定在 flag 所在 列的右方 ,即 flag 所在列可被消去。
  • 复杂度分析:

    • **时间复杂度O(m+n)**,m为行数,n为列数
    • 空间复杂度O(1)
  • 代码:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    // 标志数法
    class Solution2 {
    public boolean findNumberIn2DArray(int[][] matrix, int target) {
    if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
    return false;
    }
    int i = matrix.length - 1;
    int j = 0;
    while (i >= 0 && j < matrix[0].length) {
    if (target > matrix[i][j]) {
    j++;
    }else if (target < matrix[i][j]) {
    i--;
    }else if (target == matrix[i][j]) {
    return true;
    }
    }

    return false;
    }
    }