Given an integer array nums and an integer key, perform a linear search to find the first occurrence of key in nums.
Return the index of the first occurrence of key in nums, or -1 if key does not appear in the array.
You must implement the search yourself, without using any built-in search methods.
Function Signature
def linear_search(nums: list[int], key: int) -> int:
Rules
-
Indices are 0-based.
-
If
key
appears more than once, return the smallest index where it appears.
-
Do not call a built-in search method such as
list.index
.
Constraints
-
1 <= len(nums) <= 10^4
-
-10^9 <= nums[i], key <= 10^9
Examples
Input: nums = [4, 2, 7, 1, 9, 3], key = 7
Output: 2
The value 7 is at index 2, and it does not appear anywhere else.
Input: nums = [5, 1, 8, 1, 4], key = 1
Output: 1
The value 1 appears at indices 1 and 3. The first occurrence is at index 1.
Input: nums = [4, 2, 7, 1, 9, 3], key = 5
Output: -1
None of the six values equals 5, so the result is -1.