int[] arr={0,2,4,5,7,8,9,12,12,12};
对于数组arr:如果使用二分查找数字12,仅仅返回一个下标
现要求将所有符合要求的数字下标以数组形式返回
package DataStructure;
import java.util.ArrayList;
import java.util.Arrays;
/**
* Created with IntelliJ IDEA.
* Description:
* User: 86178
* Date: 2024-02-29
* Time: 12:44
*/
public class FindVal {
public static void main(String[] args) {
int[] arr={0,2,4,5,7,8,9,12,12,12};
//todo 返回下标
System.out.println("查找数字12");
System.out.println(search(arr, 0, arr.length - 1, 12 ));
System.out.println(binarySearch(arr, 0, arr.length, 12));
}
public static int search(int[] arr,int left,int right,int target){
if(left>right) return -1;
int mid=(left+right)/2;
if(target==arr[mid]) return mid;
else if(target>arr[mid]) return search(arr,mid+1,right,target);
else return search(arr,left,mid-1,target);
}
//todo 仅仅在二分查找代码上进行一些修改 当找到对应mid时候 分别向左右扫描 (注意越界问题)
public static ArrayList<Integer> binarySearch(int[] arr, int left, int right, int target){
ArrayList<Integer> nums=new ArrayList<>();
if(left>right) return nums;
int mid=(left+right)/2;
if(target==arr[mid]) {
int tmp=mid-1;
//左扫描
while(tmp>=0 && arr[tmp]==target){
nums.add(tmp);
tmp--;
}
//mid加入
nums.add(mid);
//右扫描
tmp=mid+1;
while(tmp<arr.length && arr[tmp]==target){
nums.add(tmp);
tmp++;
}
}
else if(target>arr[mid]) return binarySearch(arr,mid+1,right,target);
else {
return binarySearch(arr,left,mid-1,target);
}
return nums;
}
}