First Position of Target

本文介绍了一种在已排序数组中使用二分查找法找到指定目标值首个出现位置的算法实现,时间复杂度为O(logn)。通过具体代码示例展示了如何处理重复元素的情况,确保返回的是目标值的第一个索引。

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

For a given sorted array (ascending order) and a target number, find the first index of this number in O(log n) time complexity.

If the target number does not exist in the array, return -1.

Example

If the array is [1, 2, 3, 3, 4, 5, 10], for given target 3, return 2.

分析:
很明显的用binary search, 但是因为要找第一个,所以,我们需要判断一下。

 1 class Solution {
 2     /**
 3      * @param nums: The integer array.
 4      * @param target: Target to find.
 5      * @return: The first position of target. Position starts from 0.
 6      */
 7     public int binarySearch(int[] nums, int target) {
 8         if (nums == null || nums.length == 0) return -1;
 9         
10         int start = 0;
11         int end = nums.length - 1;
12         
13         while (start <= end) {
14             int mid = start + (end - start) / 2;
15             if (nums[mid] == target) {
16                 if (mid != 0 && nums[mid - 1] == target) {
17                     end = mid - 1;
18                 } else {
19                     return mid;
20                 }
21             } else if (nums[mid] < target) {
22                 start = mid + 1;
23             } else {
24                 end = mid - 1;
25             }
26         }
27         return -1;
28     }
29 }

参考请注明出处: cnblogs.com/beiyeqingteng/

转载于:https://www.cnblogs.com/beiyeqingteng/p/5639277.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值