LeetCode--No.74--Search a 2D Matrix

来源:互联网 发布:程序员联合开发王 编辑:程序博客网 时间:2024/05/16 09:50

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.


我的代码:

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

就是两个,二分查找。时间复杂度没问题。都是O(logn). 然而看了下别人的代码才发现自己的写的有多不简洁。
就是感觉思维还是很定式。觉得按顺序的查找,肯定是二分。那二维的自然就是两次二分。然而其实不需要。大可以把二维数组当做一维。
下面是优化后的代码-- 抄自 leetcode solution part

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

我今天真的撑死了。

我要坚持住早起去健身房锻炼。我要成为健康的宝宝。撑死我了。

再刷两道题消化消化,再去吃冻酸奶!

0 0
原创粉丝点击