[M] 240. Search a 2D Matrix II

YJ·3일 전

leetcode

목록 보기
88/100

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

문제

2D Matrix 에서 target 값 찾기
(조건: 행과 열 오름차순)

답안

public boolean searchMatrix(int[][] matrix, int target) {
	int rows = matrix.length;
	int cols = matrix[0].length;
	int x = 0;
	int y = cols - 1;
	while (x < rows && y >= 0) {
		if (matrix[x][y] == target) {
			return true;
		} else if (matrix[x][y] > target) {
			y--;
		} else {
			x++;
		}
	}
	return false;
}

풀이

맨 오른쪽 위에서 시작해서, 왼쪽으로 이동하면 숫자가 작아지고 아래로 이동하면 숫자가 커진다는 아이디어 착안 -> 이동 방향을 결정할 수 있다.

profile
Hello

0개의 댓글