Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Approach 1: Check the first and last digit in each row to see if the target is inside it. If so, search the row for the target.
- /**
- * @param {number[][]} matrix
- * @param {number} target
- * @return {boolean}
- */
- var searchMatrix = function(matrix, target) {
- var result = false;
- var height = matrix.length;
- // Check the first digit in each row.
- for (var row=0; row<height; row++) {
- var width = matrix[row].length;
- var first = matrix[row][0];
- var last = matrix[row][width - 1];
- if (target === first || target === last) {
- // Found target.
- result = true;
- break;
- }
- else if (target > first && target < last) {
- // Check this row for target.
- for (var i=1; i<width - 1; i++) {
- if (target === matrix[row][i]) {
- result = true;
- break;
- }
- }
- }
- }
- return result;
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement