34. Find First and Last Position of Element in Sorted Array

本文介绍了一种使用递归二分查找算法确定目标值在有序数组中首次与末次出现位置的方法。通过定义一个解决方案类,并实现searchRange方法来找出目标值的起始和结束索引,若未找到则返回[-1,-1]。该算法适用于编程竞赛和技术面试。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

对mid两边进行binary search 得出边界

 

 

 

 1 class Solution {
 2     public int[] searchRange(int[] nums, int target) {
 3         int[] res = {-1, -1};
 4         if(nums.length == 0) return res;
 5         int[] bi = biSearch(nums, target, 0, nums.length - 1);
 6         if(bi[0] == Integer.MAX_VALUE) {
 7             return res;
 8         }else {
 9             return bi;
10         }
11         
12     }
13     
14     public int[] biSearch(int[] nums, int target, int lo, int hi) {
15         int[] res = {Integer.MAX_VALUE, Integer.MIN_VALUE};
16         
17         while(lo <= hi) {
18             int mid = lo + (hi - lo)/2;
19             if(nums[mid] == target) {
20                 res[0] = Math.min(mid, biSearch(nums, target, lo, mid-1)[0]);
21                 res[1] = Math.max(mid, biSearch(nums, target, mid+1, hi)[1]);
22                 return res; //因为是recursive的 所以在这边就可以返回
23             }else if(nums[mid] < target) {
24                 lo = mid + 1;
25             }else {
26                 hi = mid - 1;
27             }
28         }
29         return res;
30     }
31 }

 

转载于:https://www.cnblogs.com/goPanama/p/9616661.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值