https://leetcode.com/problems/search-a-2d-matrix/description/?envType=study-plan&id=algorithm-ii
Search a 2D Matrix - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
예제1과 같이 2차원 배열과 target 이 주어졌을때, target 값이 있는지 참/거짓을 알아내는 문제이다.
즉, 2차원 배열에서 이분탐색하기
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if(matrix == null || matrix.length==0 || matrix[0].length==0) return false;
int col = matrix.length;
int row = matrix[0].length;
int start = 0;
int end = col*row-1;
while(start <= end){
int mid = (start + end)/2;
int midCol = mid/row;
int midRow = mid%row;
if(matrix[midCol][midRow] == target){
return true;
} else if(matrix[midCol][midRow] < target){
start = mid+1;
} else {
end = mid-1;
}
}
return false;
}
}
'코딩테스트 > LeetCode' 카테고리의 다른 글
[LeetCode]153. Find Minimum in Rotated Sorted Array (0) | 2022.11.07 |
---|---|
[LeetCode]54. Spiral Matrix (0) | 2022.11.04 |
[LeetCode]202. Happy Number (0) | 2022.11.03 |
[LeetCode]34. Find First and Last Position of Element in Sorted Array (0) | 2022.11.02 |
[LeetCode] 54.spiral-matrix (0) | 2022.09.01 |