classSolution{publicintsearch(int[] nums,int target){int left =0;int right = nums.length -1;while(left <= right){int mid = left +(right - left)/2;if(nums[mid]> target){
right = mid -1;}elseif(nums[mid]< target){
left = mid +1;}else{return mid;}}return-1;}}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Leetcode 34.在排序数组中查找元素的第⼀个和最后⼀个位置
题目
思路
通过二分查找的方式,找到这段区间的左边界和右边界即可
代码
classSolution{publicint[]searchRange(int[] nums,int target){int left =0;int right = nums.length -1;int[] ret ={-1,-1};if(nums.length ==0){return ret;}//查找左边界while(left < right){int mid = left +(right - left)/2;if(nums[mid]< target){
left = mid +1;}else{
right = mid;}}if(nums[left]!= target){return ret;}
ret[0]= left;
left =0;
right = nums.length -1;//查找右边界while(left < right){int mid = left +(right - left +1)/2;if(nums[mid]<= target){
left = mid;}else{
right = mid -1;}}
ret[1]= right;return ret;}}
classSolution{publicintsearchInsert(int[] nums,int target){int left =0;int right = nums.length -1;while(left < right){int mid = left +(right - left)/2;if(nums[mid]< target){
left = mid +1;}else{
right = mid;}}if(nums[right]< target){return right +1;}return left;}}
classSolution{publicintpeakIndexInMountainArray(int[] arr){int left =0;int right = arr.length -1;while(left < right){int mid = left +(right - left)/2;if(arr[mid+1]> arr[mid]){
left = mid +1;}else{
right = mid;}}return right;}}
classSolution{publicintfindPeakElement(int[] nums){int left =0;int right = nums.length -1;while(left < right){int mid = left +(right - left)/2;if(nums[mid+1]> nums[mid]){
left = mid +1;}else{
right = mid;}}return right;}}
classSolution{publicintfindMin(int[] nums){int left =0;int right = nums.length -1;while(left < right){int mid = left +(right - left)/2;if(nums[mid]> nums[right]){
left = mid +1;}else{
right = mid;}}return nums[left];}}