7. First Sighting

EasyArray

A librarian is scanning a shelf from left to right. Every book has a catalogue number, and she wants to know where on the shelf a particular book first shows up. Positions are counted from 0 at the left end.

Write a method firstIndexOf that takes the array nums of catalogue numbers and an integer target, and returns the position of the first book whose number equals target. If no book on the shelf has that number, return -1.

Example 1

Input:
nums = [4,8,15,8], target = 8
Output:
1
Explanation:

The number 8 appears at positions 1 and 3; the first sighting is at position 1.

Example 2

Input:
nums = [3,6,9], target = 7
Output:
-1
Explanation:

No book is numbered 7, so the answer is -1.

Constraints

1 ≤ nums.length ≤ 1000

-109 ≤ nums[i], target ≤ 109

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…