算法与数据结构-05-二分查找及拓展
描述
二分查找扩展:如果数组有序,且存在多个目标值,查询所有目标值索引返回。
public class Main { public static void main(String[] args) { ArrayList list = new ArrayList(); int[] arr = {1, 2, 2, 2, 3, 4, 5, 6, 7}; List list1 = binarySearch(arr, 0, arr.length, 2, list); System.out.println(Arrays.toString(list1.toArray())); } public static List<Integer> binarySearch(int[] arr, int left, int right, int findVal, List<Integer> list) { int mid = (left + right) / 2; int midVal = arr[mid]; if (findVal < midVal) { right = mid - 1; return binarySearch(arr, left, right, findVal, list); } else if (findVal > midVal) { left = mid + 1; return binarySearch(arr, left, right, findVal, list); } else { left = mid - 1; while (left >= 0) { if (arr[left] != findVal) { break; } list.add(left); left--; } list.add(mid); right = mid + 1; while (right < arr.length) { if (arr[right] != findVal) { break; } list.add(right); right++; } return list; } } }