给你一个满足下述两条属性的 m x n 整数矩阵:
每行中的整数从左到右按非递减顺序排列。
每行的第一个整数大于前一行的最后一个整数。
给你一个整数 target ,如果 target 在矩阵中,返回 true ;否则,返回 false 。
/*** @param {number[][]} matrix* @param {number} target* @return {boolean}*/
// 1、暴力求解
var searchMatrix = function(matrix, target) {var flag = 0for(var i = 0;i <matrix.length;i++){for(var j = 0;j <matrix[i].length;j++){if(matrix[i][j] == target){flag = 1break}}}if(flag ==1){return true}else{return false}};// 2、每一行进行二分法
var searchMatrix = function(matrix, target) {for (var i = 0; i < matrix.length; i++) {var left = 0;var right = matrix[i].length - 1;while (left <= right) {var mid = Math.floor(left + (right - left) / 2);if (matrix[i][mid] === target) {return true;} else if (matrix[i][mid] < target) {left = mid + 1;} else {right = mid - 1;}}}return false;
};// 3、直接将矩阵看成一维数组然后使用二分法
var searchMatrix = function(matrix, target) {var m = matrix.lengthvar n = matrix[0].lengthvar left = 0,right = m*n-1while(left <=right){var mid = Math.floor(left+(right-left)/2)var r = Math.floor(mid / n);var c = mid % nif(matrix[r][c] == target){return true}else if(matrix[r][c] > target){right = mid-1}else{left = mid+1}}return false
};