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
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].
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.