ง่าย 0 ข้อที่แก้แล้ว อัตราผ่าน 0%

Swap First and Last

Exchange the first and last items of a list.

สิ่งที่คุณจะได้เรียนรู้

  • เข้าถึงสมาชิกตัวแรกและตัวสุดท้าย
  • สลับสองค่า
  • จัดการลิสต์ที่สั้น

โจทย์

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.

เงื่อนไข

0 ≤ length ≤ 100,000

ตัวอย่าง

ตัวอย่างที่ 1
อินพุต:
items = [1, 2, 3, 4]

ผลลัพธ์ที่คาดหวัง:
expected = [4, 2, 3, 1]
อินพุต:
std::vector<long long> items = {1, 2, 3, 4};

ผลลัพธ์ที่คาดหวัง:
std::vector<long long> expected = {4, 2, 3, 1};
อินพุต:
long[] items = new long[] {1, 2, 3, 4};

ผลลัพธ์ที่คาดหวัง:
long[] expected = new long[] {4, 2, 3, 1};

คำอธิบาย

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

ตัวอย่างที่ 2
อินพุต:
items = [9]

ผลลัพธ์ที่คาดหวัง:
expected = [9]
อินพุต:
std::vector<long long> items = {9};

ผลลัพธ์ที่คาดหวัง:
std::vector<long long> expected = {9};
อินพุต:
long[] items = new long[] {9};

ผลลัพธ์ที่คาดหวัง:
long[] expected = new long[] {9};

คำอธิบาย

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

แนวทางการแก้

ลองทำเองก่อน แล้วค่อยเปิดคำใบ้ทีละข้อ

คำใบ้ 1

ต้องเปลี่ยนแค่สองปลายเท่านั้น; ตรงกลางคงเดิม

คำใบ้ 2

สร้างลิสต์ใหม่โดยเก็บช่วงกลางไว้ แล้วเอาตัวสุดท้ายมาไว้หน้าและตัวแรกไปไว้ท้าย

คำใบ้ 3

อย่าลืมว่ากรณีว่างและมี 1 ตัวควรคืนค่าเดิม

ความซับซ้อนที่คาดหวัง

เวลา O(n), หน่วยความจำเพิ่ม O(n)

แหล่งอ้างอิง

โจทย์นี้ปรับให้เหมาะกับ CodeUtility กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน

เรียนรู้จากคนอื่น

แนวทางจากชุมชน

ยังไม่มีวิธีทำที่เผยแพร่ ลองแก้โจทย์นี้เพื่อแชร์วิธีแรก