Given a list of integers nums, swap each consecutive even indexes with each other, and swap each consecutive odd indexes with each other.
Example 1
Inputnums = [0, 1, 2, 3, 4, 5, 6, 7, 8]
Output[2, 3, 0, 1, 6, 7, 4, 5, 8]
Explanation0 and 2 gets swapped
1 and 3 gets swapped
4 and 6 gets swapped
5 and 7 gets swapped
8 remains the same
Consecutive Pair Swapping Algorithm
We can group array elements into four, and do the Consecutive Pair Swapping. For the last group which is less than 4 but greater than 2, we can do one more swap.
vector<int> swapConsecutivePairs(vector<int>& nums) {
int i = 0;
for (; i + 3 < nums.size(); i += 4) {
swap(nums[i], nums[i + 2]);
swap(nums[i + 1], nums[i + 3]);
}
if (i + 2 < nums.size()) {
swap(nums[i], nums[i + 2]);
}
return nums;
}
The time complexity is O(N) and the space requirement is O(1) constant.
–EOF (The Ultimate Computing & Technology Blog) —
Last Post: Teaching Kids Programming - Introduction to Venn Graph and Set in Python (Check Unique String)
Next Post: Two Algorithms to Determine a Palindrome Linked List using a Stack