[M] 74. Search a 2D Matrix

YJ·4일 전

leetcode

목록 보기
87/100

https://leetcode.com/problems/search-a-2d-matrix/

문제

2D matrix 에서 target 값 찾기.
(조건: 각 행은 non-decreasing order, 그리고 이전 행의 마지막 값보다 현재 행의 첫번째 값이 더 크다.)

답안

public boolean searchMatrix(int[][] matrix, int target) {
	int m = matrix.length;
	int n = matrix[0].length;
        
	int left = 0;
	int right = m * n - 1;
	while (left <= right) {
		int mid = left + (right - left) / 2;
		int row = mid / n;
		int col = mid % n;
		if (matrix[row][col] == target) {
			return true;
		} else if (matrix[row][col] < target) {
			left = mid + 1;
		} else {
			right = mid - 1;
		}
	}
	return false;
}

메모

matrix 의 1행 1열부터 m행 n열까지 숫자를 매기면
row 는 열로 / 한 값, col 은 열로 %한 값으로 표현 가능하다.
여기서 Binary Search 해주면 됨.

profile
Hello

0개의 댓글