Tutte le sfide
Facile 0 risolte 0% di accettazione

First Negative Index

Find where the first negative number appears.

Cosa imparerai

  • Cercare in una lista dall'inizio
  • Restituire appena si trova una corrispondenza
  • Restituire -1 se non c'è nessuna corrispondenza

Problema

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

Ti serve solo la prima posizione in cui un valore è sotto zero.

Suggerimento 2

Scorri da sinistra a destra e fermati appena ne trovi uno.

Suggerimento 3

Se non appare nessun valore negativo, assicurati di restituire il valore per il caso mancante.

Complessità attesa

tempo O(n), spazio aggiuntivo O(1)

Riferimenti

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

Impara dagli altri

Soluzioni della community

Nessuna soluzione pubblicata. Risolvi questa sfida per condividere la prima.