基本思想:
二分查找要求待查找数组为有序数组
每一轮查找比较数组中间的数,若查找成功即返回,否则按照待查找数和中间数的大小关系,对前后两个子数组进行递归查找
以此类推,直到找到目标元素,返回目标元素下标,否则查找失败返回-1
若待查找元素在数组中存在多个,在查找到目标元素后,对目标元素左右进行遍历,将与目标元素相等的所有元素的下标都存入一个数组或集合中,返回即可
代码实现:
//二分查找
public int binarySearch(int value) {
return binarySearch(0, array.length - 1, value);
}
public int binarySearch(int left, int right, int value) {
if (left > right) {
return -1;
}
int mid = (left + right) / 2;
if (value < array[mid]) {
return binarySearch(left, mid - 1, value);
} else if (value > array[mid]) {
return binarySearch(mid + 1, right, value);
} else {
return mid;
}
}
//二分查找(可查找多个相同元素)
public HashSet<Integer> superBinarySearch(int value) {
return superBinarySearch(0, array.length - 1, value);
}
public HashSet<Integer> superBinarySearch(int left, int right, int value) {
if (left > right) {
return new HashSet<Integer>();
}
int mid = (left + right) / 2;
if (value < array[mid]) {
return superBinarySearch(left, mid - 1, value);
} else if (value > array[mid]) {
return superBinarySearch(mid + 1, right, value);
} else {
HashSet<Integer> hashSet = new HashSet<>();
int temp = mid - 1;
while (temp >= 0 && array[temp] == value) {
hashSet.add(temp);
temp--;
}
hashSet.add(mid);
temp = mid + 1;
while (temp <= array.length - 1 && array[temp] == value) {
hashSet.add(temp);
temp++;
}
return hashSet;
}
}
时间复杂度:O(logn)