zoukankan      html  css  js  c++  java
  • Java for LeetCode 074 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.

    解题思路:

    二分查找即可,JAVA实现如下:

        public boolean searchMatrix(int[][] matrix, int target) {
            if (matrix.length == 0 || matrix[0].length == 0)
    			return false;
    		int up = 0, down = matrix.length-1, left = 0, right = matrix[0].length-1;
    		while (up < down) {
    			if(target>matrix[(up+down)/2][0]){
    				up=(up+down)/2;
    				if(target>matrix[up][matrix[0].length-1])
    					up++;
    				else break;
    			}
    			else if(target<matrix[(up+down)/2][0])
    				down=(up+down)/2-1;
    			else return true;
    		}
    		while(left<right){
    			if(target>matrix[up][(left+right)/2])
    				left=(left+right)/2+1;
    			else if(target<matrix[up][(left+right)/2])
    				right=(left+right)/2-1;
    			else return true;
    		}
    		return target==matrix[up][left];
        }
    

     当然,也可以只用两个指针表示,JAVA实现如下:

    	public boolean searchMatrix(int[][] matrix, int target) {
    		if (matrix.length == 0 || matrix[0].length == 0)
    			return false;
            int l = 0, r = matrix.length * matrix[0].length - 1, mid = 0;
            while (l < r) {
                mid = l + (r - l) / 2;
                if (matrix[mid/matrix[0].length][mid%matrix[0].length] < target)
                    l = mid + 1;
                else if (matrix[mid/matrix[0].length][mid%matrix[0].length] > target)
                    r = mid;
                else return true;
            }
            return matrix[l/matrix[0].length][l%matrix[0].length] == target;
        }
    
  • 相关阅读:
    hdu 1269 迷宫城堡 (并查集)
    hdu 1272 小希的迷宫 (深搜)
    hdu 1026 Ignatius and the Princess I (深搜)
    hdu 1099 Lottery
    hdu 1068 Girls and Boys (二分匹配)
    几个基础数位DP(hdu 2089,hdu 3555,uestc 1307 windy 数)
    hdu 1072 Nightmare (广搜)
    hdu 1398 Square Coins (母函数)
    hdu 1253 胜利大逃亡 (深搜)
    hdu 1115 Lifting the Stone (求重心)
  • 原文地址:https://www.cnblogs.com/tonyluis/p/4509397.html
Copyright © 2011-2022 走看看