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) 贪心算法

相关推荐
江畔柳前堤5 小时前
大语言模型分布式训练:从并行策略到万卡工程的系统梳理
人工智能·分布式·深度学习·算法·目标检测·机器学习·语言模型
Doraemomo5 小时前
数据结构-环形链表
java·数据结构·链表
Forever Nore6 小时前
LeetCode 4 寻找两个正序数组的中位数 - 二分
算法·leetcode
罗西的思考8 小时前
【OpenClaw具身硬件】MiniClaw 阅读笔记---(1)基础
人工智能·算法·机器学习
蛋先生DX9 小时前
大模型参数存储格式揭秘:BF不是男朋友
深度学习·算法·llm
爱跳舞的烤冷面9 小时前
自学嵌入式第22天(数据结构——哈希)
数据结构·算法·哈希算法
猎嘤一号10 小时前
博弈论(Game Theory)的理论、算法与工程
人工智能·算法·安全·博弈论
月光船幽幽10 小时前
影子模式下保护 logits 不被修改
人工智能·python·算法
马拉AI10 小时前
腾讯开源 Agent 记忆系统,AI“换对话就忘”的问题有了新解法(附安装使用教程)
人工智能·算法·开源·科研
MC皮蛋侠客11 小时前
Redis 系列(一):全景与最小闭环——从 `SET` 命令到内存数据结构
数据结构·数据库·redis