“Cari dalam matriks 2D” Kode Jawaban

Cari matriks 2D

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;
    }
}
Prabhu Kiran Konda

Cari dalam matriks 2D

// 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;
    }
}
Prabhu Kiran Konda

Jawaban yang mirip dengan “Cari dalam matriks 2D”

Pertanyaan yang mirip dengan “Cari dalam matriks 2D”

Lebih banyak jawaban terkait untuk “Cari dalam matriks 2D” di Java

Jelajahi jawaban kode populer menurut bahasa

Jelajahi bahasa kode lainnya