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 :: types of classes in java 
Java :: java file path linux 
Java :: calculate standard deviation in java 
Java :: log4j2.properties file need to save in spring boot application 
Java :: java, how to find the most repeated character 
Java :: java float 
Java :: maven set repository location command line 
Java :: thymeleaf spring boot dependency for mail 
Java :: 1.13. programacion orientada a objetos en java 
Java :: int in string umwandeln 
Java :: write ajva program to vheck if anumber is less than 20 and greater than 5. It generates the exception out of range otherwise. If the number is within the range , then it displays the square of that number. 
Java :: java non-breajubg soace remove 
Java :: LocalRegistry java rebind() java8 
Sql :: codeigniter print last sql query 
Sql :: change nls_date_format 
Sql :: identity insert on sql server 
Sql :: stop mysql 
Sql :: psql: error: could not connect to server: No such file or directory 
Sql :: could not find driver (SQL: PRAGMA foreign_keys = ON;) 
Sql :: ci last query 
Sql :: list tables sqlite 
Sql :: postgres alter user password 
Sql :: postgresql truncate cascade restart identity 
Sql :: tsql merge example 
Sql :: create table oracle 
Sql :: mssql current date 
Sql :: sql last 7 days 
Sql :: start mysql server 
Sql :: mysql take number in string 
Sql :: MySql get fields of table 
ADD CONTENT
Topic
Content
Source link
Name
7+2 =