Tutte le sfide
Facile 0 risolte 0% di accettazione

Swap First and Last

Exchange the first and last items of a list.

Cosa imparerai

  • Accedere al primo e all'ultimo elemento
  • Scambiare due valori
  • Gestire liste corte

Problema

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

Solo le due estremità devono cambiare; tutto il resto resta invariato.

Suggerimento 2

Crea una nuova lista tenendo la parte centrale e mettendo prima l’ultimo elemento, poi il primo.

Suggerimento 3

Ricorda che i casi vuoto e con un solo elemento vanno restituiti invariati.

Complessità attesa

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

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.