boolsearchMatrix(vector<vector<int>>& matrix, int target){ int row = matrix.size(); if (!row)returnfalse; int col = matrix[0].size(); if (!col)returnfalse;
int up = 0, down = row-1, mid = 0; while (up <= down) { mid = (up + down) / 2; if (matrix[mid][0] == target)returntrue; elseif (matrix[mid][0] > target) down = mid - 1; elseif (matrix[mid][col - 1] < target) { up = mid + 1; } else break; } int left = 0, right = col-1, center; while (left <= right) { center = (left + right) / 2; if (matrix[mid][center] == target)returntrue; elseif (matrix[mid][center] < target)left = center+1; else right = center-1; } returnfalse; }
下面是修改之前找行数的while循环。修改之后的明显时间上快了许多。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
while (up <= down) { mid = (up + down) / 2; if (matrix[mid][0] > target) down = mid-1; elseif (matrix[mid][0] < target) { if (mid<row - 1 && matrix[mid + 1][0]>target) break; up = mid+1; } else returntrue; }