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

2023-11-11每日一题

一、题目编号

复制代码
765. 情侣牵手

二、题目链接

点击跳转到题目位置

三、题目描述

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

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

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

示例 1:

在这里插入图片描述

示例 2:

提示:

  • 2n == row.length
  • 2 <= n <= 30
  • n 是偶数
  • 0 <= rowi < 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) 贪心算法

相关推荐
邵奈一20 分钟前
GPT-6.1 Terra速度是Sol的3倍,价格减半
算法
RaaS10021 分钟前
Node.js Brotli RCE 漏洞自查指南:fetch、undici、axios 都在影响面,三分钟确认你的版本
人工智能·深度学习·算法
shehuiyuelaiyuehao35 分钟前
算法56,重排链表
数据结构·算法·链表
qq_452396231 小时前
第四篇:《索引原理与实战:B-tree、Hash、GIN、GiST、BRIN》
算法·哈希算法·gin
西索斯coding2 小时前
Qwen3-Max 与 Qwen-Plus:60 个真实修复任务评测方案
大数据·网络·算法·ai
INGNIGHT2 小时前
440 · 背包问题(三)(无限次数)
算法·leetcode·动态规划
suhan2 小时前
【数据结构】七、查找:1.查找的概念、线性结构查找(顺序、折半(二分)、插值、稠密、分块、倒排)
数据结构·算法·排序算法
极客 - L U2 小时前
卡尔曼滤波从零到精通
c语言·数据结构·单片机·嵌入式硬件·mcu
killerbasd3 小时前
总结 10.26
算法