[算法][LeetCode]Search a 2D Matrix——二維數組的二分查找


題目要求

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

 

  • Integers in each row are sorted from left to right.
  • The first integer of each row is greater than the last integer of the previous row.

 

For example,

Consider the following matrix:

[
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]

Given target = 3, return true.

分析

一開始寫的時候把他拆分成了兩個二分查找,先縱向找,再橫向找。縱向的二分查找比較復雜,要確定是在某個坐標上,或者在兩個坐標之間。

后來找到一個更好的方法,就是把二維數組的坐標轉化成一位數組,整體進行二分查找,程序更簡單,復雜度也更低了。

Java代碼

public boolean searchMatrix(int[][] matrix, int target) {

    if (matrix.length == 0 || matrix[0].length == 0) {
        return false;
    }

    int xLength = matrix[0].length;
    int min = 0;
    int max = matrix[0].length * matrix.length - 1;

    int x, y, current;
    while (min <= max) {
        current = (min + max) / 2;
        y = current / xLength;
        x = current % xLength;
        if (matrix[y][x] == target) {
            return  true;
        } else if (target < matrix[y][x]) {
            max = current - 1;
        } else {
            min = current + 1;
        }
    }

    return false;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM