2023-11-11 LeetCode每日一题(情侣牵手)

2023-11-11每日一题

一、题目编号

复制代码
765. 情侣牵手

二、题目链接

点击跳转到题目位置

三、题目描述

n 对情侣坐在连续排列的 2n 个座位上,想要牵到对方的手。

人和座位由一个整数数组 row 表示,其中 row[i] 是坐在第 i 个座位上的人的 ID。情侣们按顺序编号,第一对是 (0, 1),第二对是 (2, 3),以此类推,最后一对是 (2n-2, 2n-1)。

返回 最少交换座位的次数,以便每对情侣可以并肩坐在一起。 每次交换可选择任意两人,让他们站起来交换座位。

示例 1:

在这里插入图片描述

示例 2:

提示:

  • 2n == row.length
  • 2 <= n <= 30
  • n 是偶数
  • 0 <= row[i] < 2n
  • row 中所有元素均无重复

四、解题代码

cpp 复制代码
class Solution {
public:
    int minSwapsCouples(vector<int>& row) {
        // 每次交换不限制距离
        int n = row.size() / 2;
        vector<vector<int>> couple(n);
        for (int i = 0; i < n * 2; ++i ) {
            row[i] /= 2;
            couple[row[i]].emplace_back(i);
        }

        vector<int> couples(2 * n);     //
        for (auto coup: couple) {
            couples[coup[0]] = coup[1];
            couples[coup[1]] = coup[0];
        }

        int cnt = 0;
        for (int i = 0; i < 2 * n; i += 2) {
            if (couples[i] == i + 1) {
                continue;
            }

            int index1 = couples[i], index2 = couples[i+1];
            couples[i] = i + 1;
            couples[i+1] = i;
            couples[index1] = index2;
            couples[index2] = index1;  
            ++cnt;
        }

        return cnt;
    }
};

五、解题思路

(1) 贪心算法

相关推荐
CoovallyAIHub26 分钟前
智能“下沉”:边缘AI,更低功耗、更快响应、更强隐私,YOLO26只是开始
深度学习·算法·计算机视觉
yy_xzz1 小时前
【数据结构】大话单链表
数据结构·链表
Lear1 小时前
【链表】LeetCode 142.环形链表
算法
CoovallyAIHub1 小时前
2025目标检测模型全景图:从RF-DETR到YOLOv12,谁主沉浮?
深度学习·算法·计算机视觉
澪吟1 小时前
算法性能的核心度量:时间复杂度与空间复杂度全解析
数据结构·算法
咪咪渝粮1 小时前
108. 将有序数组转换为二叉搜索树
算法·leetcode
lzptouch1 小时前
蚁群(Ant Colony Optimization, ACO)算法
人工智能·算法·机器学习
苏纪云2 小时前
算法<C++>——双指针操作链表
c++·算法·链表·双指针
louisdlee.2 小时前
扫描线1:朴素扫描线
数据结构·c++·算法·扫描线
wan5555cn2 小时前
中国启用WPS格式进行国际交流:政策分析与影响评估
数据库·人工智能·笔记·深度学习·算法·wps