Swift solution - Binary Search


  • 0
    class Solution {
        func searchMatrix(_ matrix: [[Int]], _ target: Int) -> Bool {
            if matrix.count == 0 || matrix[0].count == 0 {
                return false
            }
            
            let n = matrix.count
            let m = matrix[0].count
            var left = 0
            var right = m * n - 1
            var middle = 0
            
            while left != right {
                middle = (left + right - 1) >> 1
                if matrix[middle / m][middle % m] < target {
                    left = middle + 1
                } else {
                    right = middle
                }
            }
            
            return matrix[right / m][right % m] == target
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.