题意:

image.png

解题思路:

  1. 思路:
  2. 1.双指针
  3. 2.(二分) O(logn)
  4. 2.1 把整个矩阵,按照行展开成一个数组,这个数组是单调递增,通过二分搜索即可
  5. 2.2 二分时可以通过整除和取模运算得到二维数组的坐标。
  6. m = count(matrix);
  7. n = count(matrix[0]);
  8. = mid / n,列 = mid % n

PHP代码实现:

  1. class Solution {
  2. /**
  3. * @param Integer[][] $matrix
  4. * @param Integer $target
  5. * @return Boolean
  6. */
  7. function searchMatrix($matrix, $target) {
  8. $n = count($matrix);
  9. $m = count($matrix[0]);
  10. $x = $n - 1; $y = 0;
  11. $count = 0;
  12. while ($x >= 0 && $y < $m) {
  13. if ($matrix[$x][$y] < $target) {
  14. $y++;
  15. } else if ($matrix[$x][$y] > $target) {
  16. $x--;
  17. } else {
  18. $count++;
  19. $x--;$y++;
  20. }
  21. }
  22. return $ocunt;
  23. }
  24. function searchMatrixBs($matrix, $target) {
  25. $m = count($matrix);
  26. $n = count($matrix[0]);
  27. $low = 0; $high = $m * $n - 1;
  28. while ($low <= $high) {
  29. $mid = $low + floor(($high - $low) >> 1);
  30. //$mid / $n = 行,$mid % $n = 列
  31. $r = $mid / $n;
  32. $c = $mid % $n;
  33. if ($target < $matrix[$r][$c]) $high = $mid - 1;
  34. else if ($target > $matrix[$r][$c]) $low = $mid + 1;
  35. else return true;
  36. }
  37. return false;
  38. }
  39. }

GO代码实现:

  1. func searchMatrix(matrix [][]int, target int) bool {
  2. searchMatrixBs(matrix, target)
  3. if len(matrix) == 0 {
  4. return false
  5. }
  6. row := len(matrix)
  7. col := len(matrix[0])
  8. i, j := row - 1, 0
  9. for i >= 0 && j < col {
  10. if matrix[i][j] == target {
  11. return true
  12. } else if matrix[i][j] > target {
  13. i--
  14. } else {
  15. j++
  16. }
  17. }
  18. return false
  19. }
  20. func searchMatrixBs(matrix [][]int, target int) bool {
  21. m, n := len(matrix), len(matrix[0])
  22. if m == 0 || n == 0 {
  23. return false
  24. }
  25. low, high := 0, m * n -1
  26. for low <= high {
  27. mid := (low + high) >> 1
  28. r := mid / n
  29. c := mid % n
  30. if target == matrix[r][c] {
  31. return true
  32. } else if target < matrix[r][c] {
  33. high = mid - 1
  34. } else {
  35. low = mid + 1
  36. }
  37. }
  38. return false
  39. }