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 小时前
2.LeetCode算法习题讲解--双指针--复写零
算法·leetcode·职场和发展
To_OC7 小时前
LC 438 找到所有字母异位词:暴力超时后,我靠滑动窗口一招搞定
javascript·算法·leetcode
白狐_7987 小时前
408数据结构第5章:二叉树遍历序列题——技巧、判断与真题型总结
数据结构
Forever Nore9 小时前
学完C语言力扣第一题做不来正常吗
数据结构·算法
hansang_IR10 小时前
【题解】LC:倍增 / 区间并查集(Range Parallel Unionfind)
c++·算法·并查集
Tisfy11 小时前
LeetCode 3731.找出缺失的元素:哈希 / 排序
算法·leetcode·哈希算法·排序·哈希表
lucas_AI12 小时前
Q-CueGraph:你的多模态大模型会 zoom,但真的知道该看哪儿吗?
人工智能·算法
kaixin_啊啊12 小时前
test_机器学习算法学习
学习·算法·机器学习
liulilittle12 小时前
MOE路由:路由(logits: top-k/8)
c++·人工智能·算法·机器学习·llm