查找是否存在某元素:
int[] target = new int[]{1,2,3,4,5,7,8,9};
需求:查找某元素返回true 或false,使用最优算法:
算法我只会二分法,应该还有别的算法更好,实现如下:
public static Boolean isHaveVal(int[] target, int value){
int min = 0;
int max = target.length -1;
int mid = ( max + min)/2;
while (target[mid] != value){
if (max < min){
return false;
}
if (target[mid] > value) {
max = mid - 1;
} else if (target[mid] < value) {
min = mid + 1;
}
mid = (max + min)/2;
}
return true;
}