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;}}
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];}}
FL Studio 21.1.0官方中文版重磅发布纯正简体中文支持,更快捷的音频剪辑及素材管理器,多样主题随心换!Mac版新增对苹果M2/1家族芯片原生支持。DAW界萌神!极富二次元造型的水果娘FL chan通过FL插件Fruity Dance登场,为其…