74/240. Search a 2D Matrix I/II

  1. 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.

思路: 给定的matrix中,下一行的头元素总是大于上一行的尾元素,整个二维数组中的元素是单调递增,一如何定位某一点的坐标, start=0, end= row*col-1; 某一点的表示matrix[index/col][index%col]。
复杂度: time: O(log(MN)) space: O(1)

public class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        if (matrix == null || matrix.length == 0) return false;
        int row = matrix.length;
        int col = matrix[0].length;
        int start = 0;
        int end = row * col - 1;
        while(start + 1 < end) {
            int mid = start + (end - start) / 2;
            int number = matrix[mid / col][mid % col];
            if (number < target) {
                start = mid;
            } else if (number > target) {
                end = mid;
            } else {
                return true;
            }
        }
        if (matrix[start / col][ start % col] == target || matrix[end / col][end % col] == target) {
            return true;
        }
        return false;

    }
}

Search a 2D Matrix II
[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]
思路: 从左下角开始 matrix[row – 1][0],往右上角搜索, 如果当前点大于target就往上走,小于target就往右走.
复杂度: time: O(m + n) space O(1)

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s