经典二分查找,给定一个升序的整形数组nums和一个目标值target,查找target在nums中的位置,如果目标值存在返回下标,否则返回-1
public class Solution { public int Search(int[] nums, int target) { return BinarySearch(nums, 0, nums.Length - 1, target); } public int BinarySearch(int[] nums, int L, int R, int target) { while (L <= R) { int mid = L + (R - L) / 2; if (nums[mid] == target) return mid; else if (nums[mid] < target) L = mid + 1; else R = mid - 1; } return -1; } }
二分查找的一个典型扩展: 给定一个升序数组和目标值,在数组中找到目标值并返回其索引,如果目标值不存在,返回它将被顺序插入的位置。只需将上述代码稍作修改即可
public class Solution { public int SearchInsert(int[] nums, int target) { int left = 0, right = nums.Length - 1; while (left <= right) { int mid = left + (right - left) / 2; if (nums[mid] == target) return mid; else if (nums[mid] > target) right = mid - 1; else left = mid + 1; } return right + 1; // return left; } }
标签:二分,target,nums,int,查找,目标值,public,left From: https://www.cnblogs.com/ayang1/p/17324849.html