Tutte le sfide
Facile 4 risolte 36.4% di accettazione

Swap First and Last

Exchange the first and last items of a list.

Cosa imparerai

  • Access the first and last items
  • Swap two values
  • Handle short lists

Problema

Mostra traduzione

Return a copy of the list with its first and last elements swapped. Lists with fewer than two elements stay the same.

Implement swap_first_last(items).

Input

items: The list of integers.

Output

Return the list with the ends swapped.

Vincoli

0 ≤ length ≤ 100,000

Esempi

Esempio 1
Input:
items = [1, 2, 3, 4]

Output atteso:
expected = [4, 2, 3, 1]
Input:
std::vector<long long> items = {1, 2, 3, 4};

Output atteso:
std::vector<long long> expected = {4, 2, 3, 1};
Input:
long[] items = new long[] {1, 2, 3, 4};

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

Spiegazione

1 and 4 trade places: [4, 2, 3, 1].

Esempio 2
Input:
items = [9]

Output atteso:
expected = [9]
Input:
std::vector<long long> items = {9};

Output atteso:
std::vector<long long> expected = {9};
Input:
long[] items = new long[] {9};

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

Spiegazione

A single item has nothing to swap with: [9].

Come affrontarlo

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

Suggerimento 1

Only the two ends need to change; everything in the middle stays untouched.

Suggerimento 2

Build a new list by keeping the middle section and placing the last item first, then the first item last.

Suggerimento 3

Remember the empty and one-element cases should be returned unchanged.

Complessità attesa

O(n) time, O(n) 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 757 ms - 3/5 Vedi il codice
2 HJhettory Jurash Python 806 ms - 3/5 Vedi il codice
3 RCRiccardo Corti Python 859 ms - 4/5 Vedi il codice
4 GTGarlic The Destroyer Rust 1,545 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.