Search
 
SCRIPT & CODE EXAMPLE
 

JAVA

Search a 2D Matrix

class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        if(matrix.length == 0) return false;
        int rows = matrix.length;
        int cols = matrix[0].length;
        
        int left = 0;
        int right = rows*cols-1;
        
        while(left <= right){
            int mid = left + (right-left)/2; // calculates the mid point of 1D array.
            int midElement = matrix[mid/cols][mid%cols]; // converting midpoint of 1D array to 2D array
            if(midElement == target) return true;
            if(midElement < target) left = mid+1;
            else right = mid-1;
        }
        return false;
    }
}
Comment

Search in 2D matrix

// Search a 2D Matrix II
// https://leetcode.com/problems/search-a-2d-matrix-ii
class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        int row = 0;
        int col = matrix[0].length-1;
        
        while (row < matrix.length && col >= 0){
            if (matrix[row][col] == target) return true;
            if (matrix[row][col] < target) row++;
            else if (matrix[row][col] > target) col--;
        }
       return false;
    }
}
Comment

PREVIOUS NEXT
Code Example
Java :: how to sprint minecraft java 
Java :: resultset methods in jdbc 
Java :: button event 
Java :: arraylist remove value in java 
Java :: java reverse array 
Java :: @runwith junit 5 
Java :: code to get date and time in android 
Java :: Java Access HashMap Elements 
Java :: java swing tablecellrenderer 
Java :: coin flip in java 
Java :: android cella 20*20 java 
Java :: grepper mcm java 
Java :: interact with databse java 
Sql :: search text in all sql server stored procedure 
Sql :: oracle nls_date_format 
Sql :: mysql now format 
Sql :: django.core.exceptions.ImproperlyConfigured: mysqlclient 1.4.0 or newer is required; you have 0.10.1. 
Sql :: mysql group_concat distinct 
Sql :: mysql 3 months ago 
Sql :: wilayah indonesia database 
Sql :: sql server read uncommitted 
Sql :: to date oracle with time 
Sql :: psql connections 
Sql :: sql server last executed query 
Sql :: find table for column name in sql 
Sql :: mysql where one year ago 
Sql :: create table sql server 
Sql :: stop mysql ubuntu 
Sql :: how to add a index to live table mysql 
Sql :: mariadb show tables 
ADD CONTENT
Topic
Content
Source link
Name
8+9 =