1650005856(1).png

    1. package com.algorithm.demo.searchsorts;
    2. /**
    3. * @Author leijs
    4. * @date 2022/4/15
    5. */
    6. public class Demo2 {
    7. public static void main(String[] args) {
    8. int[][] array = new int[][]{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}};
    9. System.out.println(searchMatrix(array, 6));
    10. }
    11. public static boolean searchMatrix(int[][] array, int target) {
    12. int row = array.length;
    13. if (row == 0) {
    14. return false;
    15. }
    16. int column = array[0].length;
    17. int left = 0;
    18. int right = row * column - 1;
    19. while (left < right) {
    20. int mid = (left + right) / 2;
    21. // mid = 7
    22. // 1 2 3 4
    23. // 5 6 7 8
    24. // i是第几行 index / colunm
    25. // j是第几列 index %colunm
    26. int i = mid / column;
    27. int j = mid % column;
    28. if (array[i][j] == target) {
    29. return true;
    30. }
    31. if (array[i][j] < target) {
    32. left = mid + 1;
    33. }
    34. if (array[i][j] > target) {
    35. right = mid - 1;
    36. }
    37. }
    38. return false;
    39. }
    40. }