Example 1
- Input
- matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
- Output
- true
The value 3 sits at row 0, column 1, so the answer is true.
You are given an m by n matrix where each row is sorted and every row starts after the previous row ends, plus a target integer. Return true when the target appears in the matrix and false otherwise.
You are given an m x n integer matrix matrix with two properties: each row is sorted in non-decreasing order, and the first integer of each row is greater than the last integer of the previous row.
Given an integer target, return true if target is in matrix or false otherwise. The required solution runs in time.
m == matrix.lengthn == matrix[i].length1 <= m, n <= 100-10^4 <= matrix[i][j], target <= 10^4The value 3 sits at row 0, column 1, so the answer is true.
The target 13 lies between 11 and 16 in the second row. Neither cell equals 13, and the row boundaries rule out every other row, so return false.
The minimum-size matrix has one candidate cell, and its value equals the negative target. The inclusive search interval must examine that cell and return true.
Duplicates within a row are allowed. Both 5 values occur in row 1, so finding either is sufficient; strict separation between rows still makes the virtual sequence sorted.
Reading each row left to right and then moving to the next row gives one sorted sequence: the next row begins above the previous row's last value. In Example 1 the virtual list is [1,3,5,7,10,11,16,20,23,30,34,60]. Binary search repeatedly halves a candidate interval; integer division by the four columns converts a virtual position to its row, and the remainder gives its column. The list is a way to reason about the input, so there is no need to allocate it.
Reveal Linear Scan: intuition, complexity, and code
mid in a row of n columns converts to row mid / n and column mid % n with integer division.0 to m * n - 1 and compare matrix[row][col] against target at each step.[[1]] works because left and right both start at 0.target smaller than the first cell or larger than the last cell exhausts the range and returns false.n equals the true column count.When a 2D grid flattens into one sorted sequence, binary search over virtual indices with arithmetic mapping beats scanning every cell.