Đề bài
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.
Ràng buộc
0 ≤ length ≤ 100,000
Ví dụ
Đầu vào:
items = [1, 2, 3, 4]
Kết quả mong đợi:
expected = [4, 2, 3, 1]
Đầu vào:
std::vector<long long> items = {1, 2, 3, 4};
Kết quả mong đợi:
std::vector<long long> expected = {4, 2, 3, 1};
Đầu vào:
long[] items = new long[] {1, 2, 3, 4};
Kết quả mong đợi:
long[] expected = new long[] {4, 2, 3, 1};
Giải thích
1 and 4 trade places: [4, 2, 3, 1].
Đầu vào:
items = [9]
Kết quả mong đợi:
expected = [9]
Đầu vào:
std::vector<long long> items = {9};
Kết quả mong đợi:
std::vector<long long> expected = {9};
Đầu vào:
long[] items = new long[] {9};
Kết quả mong đợi:
long[] expected = new long[] {9};
Giải thích
A single item has nothing to swap with: [9].
Hướng tiếp cận
Hãy tự thử trước, sau đó mở từng gợi ý một.
Gợi ý 1
Only the two ends need to change; everything in the middle stays untouched.
Gợi ý 2
Build a new list by keeping the middle section and placing the last item first, then the first item last.
Gợi ý 3
Remember the empty and one-element cases should be returned unchanged.
Độ phức tạp mong đợi
O(n) time, O(n) extra space
Tham khảo
Thử thách này đã được điều chỉnh cho CodeUtility. Hãy làm theo đề bài và các ràng buộc ở trên.