Beat 99% Fast Java One Loop (1 to m*n) Solution


  • 1
    M
    public boolean searchMatrix(int[][] matrix, int target) {
    
    		int height = matrix.length;
    		int width = matrix[0].length;
    
    		int left = 0, right = height * width - 1;
    
    		int mid = 0, cur;
    		while (left <= right) {
    			mid = (left + right) / 2;
    			cur = matrix[mid / width][mid % width];
    
    			if (target < cur)
    				right = mid - 1;
    			else if (target > cur)
    				left = mid + 1;
    			else
    				return true;
    		}
    
    		return false;
    	}

  • 0
    D

    A few highlights in the code above.

    1. Treat the 2D array as 1D due to the given array's nature.
    2. Instead of checking left & right on the go, check it during return.

    Good job!


  • 0
    M

    Thank you. Actually I eliminated the second highlight by updating this a little. Don't think it looks better now?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.