参考解法https://blog.csdn.net/meng_lemon/article/details/97141897
#include<iostream> #include<stdio.h> #include<algorithm> using namespace std; int main() { int n; cin >> n; int nums[2*n]; for(int i=0; i<2*n; i++) { cin >> nums[i]; } int count = 0, left = 0, right; for(left; left<2*n; left=left+2) { right = left + 1; //找到值相等的对应元素的下标 while(right<2*n && nums[left]!=nums[right]) right++; //将对应元素与前一个元素交换位置,直到下标为left+1,即值相等两元素相邻 for(right; right>left+1; right--) { swap(nums[right-1], nums[right]); count ++; } } cout << count <<endl; return 0; }