Problem · Array
First Target Index
Learn this problemProblem statement
Given a nondecreasing integer array nums and an integer target, return the smallest index i such that nums[i] == target. Return -1 when target does not occur.
Your solution must run in O(log n) time.
Function
firstTargetIndex(nums: int[], target: int) → intExamples
Example 1
nums = [1,2,2,2,4]target = 2return = 1The target appears at indices 1, 2, and 3, so the first index is 1.
Example 2
nums = [-5,-2,0,3]target = 1return = -1The target does not occur in nums.
Example 3
nums = [7]target = 7return = 0The only element equals the target.
Constraints
1 <= nums.length <= 100000.-2147483648 <= nums[i], target <= 2147483647.numsis sorted in nondecreasing order.