74. Search a 2D Matrix

202407040946
tags: #binary-search

var searchMatrix = function(matrix, target) {
	const m = matrix.length;
	const n = matrix[0].length;
	let start = 0;
	let end = m * n - 1;
	while (start <= end) {
		const mid = Math.floor((end - start) / 2) + start;
		const midVal = matrix[Math.floor(mid / n)][mid % n];
		if (midVal === target) {
			return true;
		}
		else if (midVal < target) {
			start = mid + 1;
		}
		else {
			end = mid - 1;
		}
	}
	return false;
};

Reference

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