समस्या
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
उदाहरण
इनपुट:
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].
इनपुट:
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
बीच वाले हिस्से को जस का तस रखकर एक नई list बनाओ: आख़िरी item पहले, फिर पहला item आख़िर में।
संकेत 3
empty और one-element cases को बिना बदले लौटाना याद रखो।
अपेक्षित जटिलता
समय O(n), अतिरिक्त स्थान O(n)
संदर्भ
यह चुनौती CodeUtility के लिए अनुकूलित की गई है। ऊपर दिए गए स्टेटमेंट और सीमाओं का पालन करें।