Problème
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.
Contraintes
0 ≤ length ≤ 100,000
Exemples
Entrée :
items = [1, 2, 3, 4]
Sortie attendue :
expected = [4, 2, 3, 1]
Entrée :
std::vector<long long> items = {1, 2, 3, 4};
Sortie attendue :
std::vector<long long> expected = {4, 2, 3, 1};
Entrée :
long[] items = new long[] {1, 2, 3, 4};
Sortie attendue :
long[] expected = new long[] {4, 2, 3, 1};
Explication
1 and 4 trade places: [4, 2, 3, 1].
Entrée :
items = [9]
Sortie attendue :
expected = [9]
Entrée :
std::vector<long long> items = {9};
Sortie attendue :
std::vector<long long> expected = {9};
Entrée :
long[] items = new long[] {9};
Sortie attendue :
long[] expected = new long[] {9};
Explication
A single item has nothing to swap with: [9].
Comment l'aborder
Essayez d'abord seul, puis ouvrez les indices un par un.
Indice 1
Only the two ends need to change; everything in the middle stays untouched.
Indice 2
Build a new list by keeping the middle section and placing the last item first, then the first item last.
Indice 3
Remember the empty and one-element cases should be returned unchanged.
Complexité attendue
O(n) time, O(n) extra space
Références
Ce défi a été adapté pour CodeUtility. Suivez l'énoncé et les contraintes ci-dessus.