Problem: https://leetcode.com/problems/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

Thought:

  search last row , last column and the left matrix (I didn't consider the second property)

  If I consider the second property, search for row then search the row would be much better.(O(log(mn)))

Code C++:

class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        if (matrix.size() < 1) {
            return false;
        }
        
        int m = matrix.size(), n = matrix[0].size();
        
        if (target > matrix[m - 1][n - 1]) {
            return false;
        } else if (target == matrix[m - 1][n - 1]) {
            return true;
        }
        
        if (m == 1) {
            return binary_search(matrix[0].begin(), matrix[0].end(), target);
        }
        if (n == 1) {
            vector<int> column;
            for (int i = 0; i < matrix.size(); i++) {
                column.push_back(matrix[i][0]);
            }
            return binary_search(column.begin(), column.end(), target);
        }
        
        vector<vector<int>> corner;
        vector<int> row;
        vector<int> column;
        
        for (int i = 0; i < m - 1; i++) {
            vector<int> temp;
            for (int j = 0; j < n - 1; j++) {
                temp.push_back(matrix[i][j]);
            }
            corner.push_back(temp);
        }
        
        for (int i = 0; i < n - 1; i++) {
            row.push_back(matrix[m - 1][i]);
        }
        
        for (int i = 0; i < m - 1; i++) {
            column.push_back(matrix[i][n - 1]);
        }
        
        return binary_search(row.begin(), row.end(), target) || binary_search(column.begin(), column.end(), target) || searchMatrix(corner, target);
    }
};

 

posted on 2016-07-28 16:45  gavinXing  阅读(144)  评论(0编辑  收藏  举报