Tutte le sfide
Facile 5 risolte 83.3% di accettazione

Min and Max Together

Find the smallest and largest value in one pass.

Cosa imparerai

  • Track the minimum and maximum together
  • Return two values at once
  • Visit each element only once

Problema

Mostra traduzione

Walk through the list once and track both the smallest and the largest value.

Implement min_and_max(numbers).

Input

numbers: A non-empty list of integers.

Output

Return [smallest, largest].

Vincoli

1 ≤ length ≤ 100,000

Esempi

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

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

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

Output atteso:
long[] expected = new long[] {-2, 9};

Spiegazione

The smallest value is -2 and the largest is 9: [-2, 9].

Esempio 2
Input:
numbers = [7]

Output atteso:
expected = [7, 7]
Input:
std::vector<long long> numbers = {7};

Output atteso:
std::vector<long long> expected = {7, 7};
Input:
long[] numbers = new long[] {7};

Output atteso:
long[] expected = new long[] {7, 7};

Spiegazione

With one value it is both the smallest and largest: [7, 7].

Come affrontarlo

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

Suggerimento 1

Track the smallest and largest values as you move through the list once.

Suggerimento 2

Update your running minimum and maximum whenever you see a new extreme.

Suggerimento 3

Since the list is guaranteed non-empty, you can start from its first element.

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 LMLaura Mahlow Python 666 ms - 5/5 Vedi il codice
2 HJhettory Jurash Python 686 ms - 4/5 Vedi il codice
3 KKKaneki Ken Python 709 ms - 3/5 Vedi il codice
4 RCRiccardo Corti Python 759 ms - 5/5 Vedi il codice

Impara dagli altri

Soluzioni della community

Attenzione spoiler: 4 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.