这是我正式刷题的第一道题,很有纪念意义啊!2022/5/30 8:30 美好的开始❤️加油!
https://www.nowcoder.com/practice/abc3fe2ce8e146608e868a70efebf62e
暴力求解
自己想出来的。
public static boolean Find(int target, int[][] array) {
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
if (target == array[i][j])
return true;
}
}
return false;
}
二分查找
看了别人的思路,自己做出来了哈哈👍
public class Solution {
public boolean Find(int target, int [][] array) {
//每轮用二分查找
for (int i = 0; i < array.length; i++) {
boolean ans = binarySearch(target, array[i]);
if (ans)
return ans;
}
return false;
}
public static boolean binarySearch(int target, int[] array) {
//二分查找算法
int left = 0, right = array.length - 1, mid = (left + right) / 2;
// System.out.println(left);
// System.out.println(right);
// System.out.println(mid);
while (right >= left) {
if (array[mid] == target) {
// System.out.println("index:" + mid);
return true;
} else if (array[mid] > target) {
right = mid - 1;
mid = (left + right) / 2;
} else {
left = mid + 1;
mid = (left + right) / 2;
}
}
return false;
}
}