LeetCode: Search a 2D Matrix java

https://oj.leetcode.com/problems/search-a-2d-matrix/

Naive Solution:

public class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return false;
        
        boolean result = false;
        int m = matrix.length;
        int n = matrix[0].length;
        
        for (int i = 0; i < m; i++) {
            
            if (target < matrix[i][0]) return false;
            if (target > matrix[i][n - 1]) continue;
            
            int low = 0;
            int high = n - 1;
            int[] num = matrix[i];
            
            while (low <= high) { /*NOTICE: low == high should also take in account!*/
                
                int mid = low + (high - low) / 2;
                if (num[mid] == target) {
                    return true;
                } else {
                    if (num[mid] < target) {
                        low = mid + 1;
                    } else {
                        high = mid - 1;
                    }
                }
                
            }
        }
        
        return result;
    }
}
posted @ 2015-01-14 07:08  windlesses  阅读(155)  评论(0)    收藏  举报