Problème
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].
Contraintes
1 ≤ length ≤ 100,000
Exemples
Entrée :
numbers = [4, -2, 9, 0]
Sortie attendue :
expected = [-2, 9]
Entrée :
std::vector<long long> numbers = {4, -2, 9, 0};
Sortie attendue :
std::vector<long long> expected = {-2, 9};
Entrée :
long[] numbers = new long[] {4, -2, 9, 0};
Sortie attendue :
long[] expected = new long[] {-2, 9};
Explication
The smallest value is -2 and the largest is 9: [-2, 9].
Entrée :
numbers = [7]
Sortie attendue :
expected = [7, 7]
Entrée :
std::vector<long long> numbers = {7};
Sortie attendue :
std::vector<long long> expected = {7, 7};
Entrée :
long[] numbers = new long[] {7};
Sortie attendue :
long[] expected = new long[] {7, 7};
Explication
With one value it is both the smallest and largest: [7, 7].
Comment l'aborder
Essayez d'abord seul, puis ouvrez les indices un par un.
Indice 1
Suis les plus petites et plus grandes valeurs en parcourant la liste une seule fois.
Indice 2
Mets à jour ton minimum et ton maximum courants dès qu’une nouvelle extrémité apparaît.
Indice 3
Comme la liste est garantie non vide, tu peux partir de son premier élément.
Complexité attendue
temps O(n), espace supplémentaire O(1)
Références
Ce défi a été adapté pour CodeUtility. Suivez l'énoncé et les contraintes ci-dessus.