Problème
Find the position (counting from 0) of the first negative number in the list.
Implement first_negative_index(numbers).
Input
numbers: The list of integers.
Output
Return the index, or -1 if there are no negative numbers.
Contraintes
0 ≤ length ≤ 100,000
Exemples
Entrée :
numbers = [4, 0, -2, -7]
Sortie attendue :
expected = 2
Entrée :
std::vector<long long> numbers = {4, 0, -2, -7};
Sortie attendue :
long long expected = 2;
Entrée :
long[] numbers = new long[] {4, 0, -2, -7};
Sortie attendue :
long expected = 2;
Explication
-2 at index 2 is the first negative value.
Entrée :
numbers = [1, 2, 3]
Sortie attendue :
expected = -1
Entrée :
std::vector<long long> numbers = {1, 2, 3};
Sortie attendue :
long long expected = -1;
Entrée :
long[] numbers = new long[] {1, 2, 3};
Sortie attendue :
long expected = -1;
Explication
There are no negative numbers, so the answer is -1.
Comment l'aborder
Essayez d'abord seul, puis ouvrez les indices un par un.
Indice 1
You only need the first position where a value is below zero.
Indice 2
Scan from left to right and stop as soon as you find one.
Indice 3
If no negative value appears, be sure to return the missing-case value.
Complexité attendue
O(n) time, O(1) extra space
Références
Ce défi a été adapté pour CodeUtility. Suivez l'énoncé et les contraintes ci-dessus.