Tutte le sfide
Facile 3 risolte 60.0% di accettazione

First Negative Index

Find where the first negative number appears.

Cosa imparerai

  • Search a list from the start
  • Return as soon as you find a match
  • Return -1 when nothing matches

Problema

Mostra traduzione

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.

Vincoli

0 ≤ length ≤ 100,000

Esempi

Esempio 1
Input:
numbers = [4, 0, -2, -7]

Output atteso:
expected = 2
Input:
std::vector<long long> numbers = {4, 0, -2, -7};

Output atteso:
long long expected = 2;
Input:
long[] numbers = new long[] {4, 0, -2, -7};

Output atteso:
long expected = 2;

Spiegazione

-2 at index 2 is the first negative value.

Esempio 2
Input:
numbers = [1, 2, 3]

Output atteso:
expected = -1
Input:
std::vector<long long> numbers = {1, 2, 3};

Output atteso:
long long expected = -1;
Input:
long[] numbers = new long[] {1, 2, 3};

Output atteso:
long expected = -1;

Spiegazione

There are no negative numbers, so the answer is -1.

Come affrontarlo

Prova prima da solo, poi apri un suggerimento alla volta.

Suggerimento 1

You only need the first position where a value is below zero.

Suggerimento 2

Scan from left to right and stop as soon as you find one.

Suggerimento 3

If no negative value appears, be sure to return the missing-case value.

Complessità attesa

O(n) time, O(1) extra space

Riferimenti

Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.

La migliore soluzione superata di ogni programmatore. Le più veloci, leggere e meglio valutate stanno in alto.

# Programmatore Linguaggio Tempo Memoria Voto dell'IA Soluzione
1 RCRiccardo Corti Python 843 ms - 5/5 Vedi il codice
2 LMLaura Mahlow Python 860 ms - 5/5 Vedi il codice
3 BBoomTris C++ 3,711 ms - 4/5 Vedi il codice

Impara dagli altri

Soluzioni della community

Attenzione spoiler: 3 soluzioni complete sotto Prova prima a risolverla da solo. Puoi comunque sbirciare il codice degli altri sviluppatori e le revisioni dell'IA. Accedi e risolvi la sfida per partecipare alla discussione.