当前位置: 首页 > news >正文

Leetcode1128. 等价多米诺骨牌对的数量

Every day a Leetcode

题目来源:1128. 等价多米诺骨牌对的数量

解法1:暴力

代码:

class Solution
{
public:int numEquivDominoPairs(vector<vector<int>> &dominoes){int n = dominoes.size(), count = 0;for (int i = 0; i < n - 1; i++)for (int j = i + 1; j < n; j++){if (dominoes[i] == dominoes[j] || dominoes[i] == vector<int>(dominoes[j].rbegin(), dominoes[j].rend()))count++;}return count;}
};

结果:

超时了。

复杂度分析:

时间复杂度:O(n2),其中 n 是数组 dominoes 的长度。

空间复杂度:O(1)。

解法2:哈希

遍历数组 dominoes,对每一个多米诺骨牌 domino 排序,这样就保证等价的多米诺骨牌能存储在一个哈希值里。用一个形如 unordered_map<vector<int>, int> 的哈希表,记录等价的多米诺骨牌的数量。

结果报错了:

error: call to implicitly-deleted default constructor of ‘unordered_map<vector<int>, int>‘

用 map 就行了。

具体办法:error: call to implicitly-deleted default constructor of ‘unordered_map<vector<int>, int>‘

设一种多米诺骨牌的出现次数为 n,则等价的骨牌对 (i, j) 的数量为 C(n, 2) = n * (n - 1) / 2。答案为等价的骨牌对 (i, j) 的数量的总和。

代码:

/** @lc app=leetcode.cn id=1128 lang=cpp** [1128] 等价多米诺骨牌对的数量*/// @lc code=start
// class Solution
// {
// public:
//     int numEquivDominoPairs(vector<vector<int>> &dominoes)
//     {
//         int n = dominoes.size(), count = 0;
//         for (int i = 0; i < n - 1; i++)
//             for (int j = i + 1; j < n; j++)
//             {
//                 if (dominoes[i] == dominoes[j] || dominoes[i] == vector<int>(dominoes[j].rbegin(), dominoes[j].rend()))
//                     count++;
//             }
//         return count;
//     }
// };class Solution
{
public:int numEquivDominoPairs(vector<vector<int>> &dominoes){int n = dominoes.size();map<vector<int>, int> hash;for (vector<int> &domino : dominoes){sort(domino.begin(), domino.end());hash[domino]++;}int count = 0;for (auto it = hash.begin(); it != hash.end(); it++){int freq = it->second;// 组合:C(n, 2) = n * (n - 1) / 2count += freq * (freq - 1) / 2;}return count;}
};
// @lc code=end

结果:

在这里插入图片描述

复杂度分析:

时间复杂度:O(n),其中 n 是数组 dominoes 的长度。

空间复杂度:O(n),其中 n 是数组 dominoes 的长度。

http://www.lryc.cn/news/217301.html

相关文章:

  • Dev-C调试的基本方法2-2
  • 企业之间的竞争,ISO三体系认证至关重要!
  • node教程(四)Mongodb+mongoose
  • 作为一个初学者,该如何入门大模型?
  • 编译支持GPU的opencv,并供python的import cv2调用
  • Bug记录
  • web3 React dapp中编写balance组件从redux取出并展示用户资产
  • BIOS开发笔记 - DDR中的时序参数
  • 语义分割 - 简介
  • ch0_OSI 七层网络协议介绍
  • 超声波俱乐部分享:百度世界大会点燃AI创业者新希望
  • 【项目管理】项目计划中常见影响进度的风险汇总
  • Apache HttpClient库编写的Scala程序
  • Java 为什么不推荐在 while 循环中使用 sleep() 我悟了
  • 编程新手的犯错之路
  • 高级 Python:函数
  • 【学习笔记】[PA2019] Osady i warownie 2
  • Flask——接口路由技术
  • Dubbo篇---第一篇
  • powermock-成员变量赋值
  • Axios请求成功和失败时分别执行哪个函数?
  • 【Linux】进程概念III --fork函数解析
  • 关闭 Android SplashScreen(闪屏)
  • react_16
  • 前端性能分析工具
  • 根据Aurora发送时序,造Aurora 数据包,从而进行AXIS接口数据位宽转换仿真
  • java后端响应结果Result
  • react_11
  • AI:52-基于深度学习的垃圾分类
  • [shell,hive] 在shell脚本中将hiveSQL分离出去