leetcode 765. Couples Holding Hands 情侣牵手
2026/6/9 4:38:13 网站建设 项目流程

Problem: 765. Couples Holding Hands 情侣牵手

https://leetcode.com/problems/couples-holding-hands/description/comments/1923078/

解题过程

贪心,每次遇到不匹配的,拿后面匹配的交换即可,最后统计次数,就可以,官方题解的并查集

Code

class Solution { public: int minSwapsCouples(vector<int>& row) { int num = 0; for(int i = 0; i < row.size(); i += 2) { if(row[i]%2==0 && row[i+1]!=row[i]+1) { for(int j = i+2; j < row.size(); j++) { if(row[j]==row[i]+1) { swap(row[j], row[i+1]); num++; break; } } } else if(row[i]%2==1 && row[i+1]!=row[i]-1) { for(int j = i+2; j < row.size(); j++) { if(row[j]==row[i]-1) { swap(row[j], row[i+1]); num++; break; } } } } return num; } };

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询