Golang, Binary Search solution, very easy to understand .


  • 0
    func searchMatrix(matrix [][]int, target int) bool {
    	var right_bound int = -1
    
    	for r := 0; r < len(matrix); r++ {
    		s := 0
    		e := 0
    
    		if right_bound == -1 {
    			e = len(matrix[r]) - 1
    			right_bound = len(matrix[r]) - 1
    		} else {
    			e = right_bound
    		}
    
    		for s <= e {
    			m := (s + e) / 2
    			v := matrix[r][m]
    
    			if target == v {
    				return true
    			} else if target < v {
    				right_bound = m - 1
    				e = m - 1
    			} else {
    				s = m + 1
    			}
    		}
    	}
    
    	return false
    }
    
    
    

  • 0
    R

    Simple version based on top answers:

    func searchMatrix(matrix [][]int, target int) bool {
        if matrix == nil || len(matrix) < 1 || len(matrix[0]) < 1 { return false }
        m := len(matrix)
        n := len(matrix[0])
        i := 0
        j := n - 1
        for  i < m && j >= 0 {
            if matrix[i][j] == target { return true
            } else if matrix[i][j] < target {
                i++
            } else {
                j--
            }
        }
        return false
    }
    

Log in to reply
 

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