LeetCode:Search a 2D Matrix

来源:互联网 发布:小明发布686永久域名 编辑:程序博客网 时间:2024/05/19 09:03

推荐参照:Leetcode题目难度等级及面试频率总结

题目描述: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.

思路一:

  首先,定位target值所在行,然后对该行进行二分查找即可。

    public boolean searchMatrix(int[][] matrix, int target) {        boolean isExist = false;        int row = matrix.length;//行数        int col = matrix[0].length;//列数        int target_row = 0;        int i = col - 1;        if(row * col == 0)            return false;        for(int j = 0 ;j < row; j ++){            ///寻找目标值所在行数            if(target >= matrix[j][0] && target <= matrix[j][i]){                isExist = true;                target_row = j;                break;            }        }        if(!isExist)            return false;        //在指定行进行二分查找        int low = 0;        int high = col - 1;        while(low <= high){            int mid = (low+high)/2;            if(matrix[target_row][mid]>target)                high = mid -1;            else if(matrix[target_row][mid] == target)                return true;            else                low = mid + 1;        }        return false;    }

思路二:

首先选取右上角数字,如果该数字等于要查找的数字,查找过程结束;如果该数字大于要查找的数字,去掉此数字所在列;如果该数字小于要查找的数字,则去掉该数字所在行。重复上述过程直到找到要查找的数字,或者查找范围为空。

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

思路三:

把二维的表格看成是一维的数组

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

  Any comments greatly appreciated.

0 0