首页 > ACM题库 > LeetCode > LeetCode-Search a 2D Matrix[查找]
2014
11-18

LeetCode-Search a 2D Matrix[查找]

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.

标签: Array Binary Search
分析

二分查找。

代码1

// LeetCode, Search a 2D Matrix
// 时间复杂度O(logn),空间复杂度O(1)
class Solution {
public:
    bool searchMatrix(const vector<vector<int>>& matrix, int target) {
        if (matrix.empty()) return false;
        const size_t  m = matrix.size();
        const size_t n = matrix.front().size();

        int first = 0;
        int last = m * n;

        while (first < last) {
            int mid = first + (last - first) / 2;
            int value = matrix[mid / n][mid % n];

            if (value == target)
                return true;
            else if (value < target)
                first = mid + 1;
            else
                last = mid;
        }

        return false;
    }
};

Java代码:

public class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        int row=0;
        int m = matrix.length;
        int n = matrix[0].length;
        int col=n-1;
        while(row < m && col >= 0){
            if(matrix[row][col] == target)
                return true;
                else if(matrix[row][col] < target)
                row++;
                else col--;
        }
        return false;
    }
}

  1. 算法是程序的灵魂,算法分简单和复杂,如果不搞大数据类,程序员了解一下简单点的算法也是可以的,但是会算法的一定要会编程才行,程序员不一定要会算法,利于自己项目需要的可以简单了解。