package BisectionMethod; /** * 704.二分查找 * 给定一个n个元素有序的(升序)整型数组 nums 和一个目标值target ,写一个函数搜索 nums 中的 target, * 如果目标值存在返回下标,否则返回 -1。 */ /** * 思路:设定左右指针 * 找出中间位置,并判断该位置值是否等于 target * nums[mid] == target 则返回该位置下标 * nums[mid] > target 则右侧指针移到中间 * nums[mid] < target 则左侧指针移到中间 * 时间复杂度:O(logN) * */ public class BinarySearch { public static void main(String[] args) { int arr[] = {1,5,2,4,6,7,34,22}; int target = 5; int result = binarySearch(arr,target); System.out.println(result); } public static int binarySearch(int[] arr, int target) { int left = 0; int right = arr.length - 1; while (left <= right) { int mid = (left + right) / 2; int num = arr[mid]; if (num == target) { return mid; } else if (num > mid) { right = mid - 1; } else { left = mid + 1; } } return -1; } }
标签:arr,target,nums,int,mid,BinarySearch From: https://www.cnblogs.com/lipinbigdata/p/17278249.html