题目:
给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。 你的算法时间复杂度必须是 O(log n) 级别。 如果数组中不存在目标值,返回 [-1, -1]。 示例 1: 输入: nums = [5,7,7,8,8,10], target = 8 输出: [3,4] 示例 2: 输入: nums = [5,7,7,8,8,10], target = 6 输出: [-1,-1]思路:先晒一个大佬的文章地址:https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/solution/er-fen-cha-zhao-suan-fa-xi-jie-xiang-jie-by-labula/巨详细,里面包括了写二分的各种误区。
总结一下:
二分搜索可分为查询一个值,和查询一个范围(也就是找到左边界和右边界),这二者的区别还是挺大的普通的二分查找模板:
int binarySearch(int[] nums, int target) { int left = 0, right = ...; while(...) { int mid = (right + left) / 2; if (nums[mid] == target) { ... } else if (nums[mid] < target) { left = ... } else if (nums[mid] > target) { right = ... } } return ...; }查询左边界的模板:
//寻找左边界 public static int findLeft(int nums[],int target){ int left=0; int right=nums.length; while(left<right){ int mid=left+(right-left)/2; if(nums[mid]==target){ right=mid; }else if(nums[mid]<target){ left=mid+1; }else{ right=mid; } } //越界 if (left == nums.length) return -1; //得到的数的下标的数不等于target return nums[left] == target ? left : -1; }查找有边界的模板:
//寻找右边界 public static int findRight(int nums[],int target){ int left=0; int right=nums.length; while(left<right){ int mid=left+(right-left)/2; if(nums[mid]==target){ left=mid+1; }else if(nums[mid]<target){ left=mid+1; }else{ right=mid; } } if (left == 0) return -1; return nums[left-1] == target ? (left-1) : -1; }最后的代码:
class Solution { public static int[] searchRange(int[] nums, int target) { if(nums==null ||nums.length==0){ return new int[]{-1,-1}; } return new int[]{findLeft(nums,target),findRight(nums,target)}; } //寻找左边界 public static int findLeft(int nums[],int target){ int left=0; int right=nums.length; while(left<right){ int mid=left+(right-left)/2; if(nums[mid]==target){ right=mid; }else if(nums[mid]<target){ left=mid+1; }else{ right=mid; } } if (left == nums.length) return -1; return nums[left] == target ? left : -1; } //寻找右边界 public static int findRight(int nums[],int target){ int left=0; int right=nums.length; while(left<right){ int mid=left+(right-left)/2; if(nums[mid]==target){ left=mid+1; }else if(nums[mid]<target){ left=mid+1; }else{ right=mid; } } if (left == 0) return -1; return nums[left-1] == target ? (left-1) : -1; } }