LeetCode – 74. Search a 2D Matrix

題目連結: https://leetcode.com/problems/search-a-2d-matrix/

// Test cases:
// matrix: [], target = 1
// matrix: m x n matrix, target = 6, output: true
// matrix: m x n matrix, target = 6, output: false

    func searchMatrix(_ matrix: [[Int]], _ target: Int) -> Bool {
        guard !matrix.isEmpty else { return false }
        let rowCount = matrix.count
        let colCount = matrix[0].count
        var left = 0
        var right = rowCount * colCount - 1
        while left <= right {
        	let mid = (left + right) / 2
        	let midRow = mid / colCount
        	let midCol = mid % colCount
        	if matrix[midRow][midCol] == target {
        		return true
        	} else if matrix[midRow][midCol] > target {
        		right = mid - 1
        	} else {
        		left = mid + 1
        	}
        }
        return false
    }