这是我正式刷题的第一道题,很有纪念意义啊!2022/5/30 8:30 美好的开始❤️加油!

https://www.nowcoder.com/practice/abc3fe2ce8e146608e868a70efebf62e

暴力求解

自己想出来的。

  1. public static boolean Find(int target, int[][] array) {
  2. for (int i = 0; i < array.length; i++) {
  3. for (int j = 0; j < array[i].length; j++) {
  4. if (target == array[i][j])
  5. return true;
  6. }
  7. }
  8. return false;
  9. }

二分查找

看了别人的思路,自己做出来了哈哈👍
image.png

  1. public class Solution {
  2. public boolean Find(int target, int [][] array) {
  3. //每轮用二分查找
  4. for (int i = 0; i < array.length; i++) {
  5. boolean ans = binarySearch(target, array[i]);
  6. if (ans)
  7. return ans;
  8. }
  9. return false;
  10. }
  11. public static boolean binarySearch(int target, int[] array) {
  12. //二分查找算法
  13. int left = 0, right = array.length - 1, mid = (left + right) / 2;
  14. // System.out.println(left);
  15. // System.out.println(right);
  16. // System.out.println(mid);
  17. while (right >= left) {
  18. if (array[mid] == target) {
  19. // System.out.println("index:" + mid);
  20. return true;
  21. } else if (array[mid] > target) {
  22. right = mid - 1;
  23. mid = (left + right) / 2;
  24. } else {
  25. left = mid + 1;
  26. mid = (left + right) / 2;
  27. }
  28. }
  29. return false;
  30. }
  31. }