代码随想录leetcode200题之哈希表

目录

  • 1 介绍
  • 2 训练
  • 3 参考

1 介绍

本博客用来记录代码随想录leetcode200题中哈希表部分的题目。

2 训练

题目1:242. 有效的字母异位词

C++代码如下,

class Solution {
public:
    bool isAnagram(string s, string t) {
        vector<int> cnt1(26, 0), cnt2(26,0);
        for (char c : s) cnt1[c-'a']++;
        for (char c : t) cnt2[c-'a']++;

        for (int i = 0; i < 26; ++i) {
            if (cnt1[i] != cnt2[i]) return false;
        }
        return true;
    }
};

python3代码如下,

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        cnt1 = [0] * 26
        cnt2 = [0] * 26

        for c in s:
            cnt1[ord(c)-ord('a')] += 1
        
        for c in t:
            cnt2[ord(c)-ord('a')] += 1
        
        for i in range(26):
            if cnt1[i] != cnt2[i]:
                return False
        return True

题目2:349. 两个数组的交集

C++代码如下,

class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        unordered_map<int,bool> visited1;
        for (auto x : nums1) visited1[x] = true;

        vector<int> res;
        unordered_map<int,bool> visited2;
        for (auto x : nums2) {
            if (visited1[x] == true) {
                if (visited2[x] == false) {
                    res.emplace_back(x);
                    visited2[x] = true;
                }
            } 
        }
        return res;
    }
};

python3代码如下,

class Solution:
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        vis1 = collections.defaultdict(bool)
        for x in nums1:
            vis1[x] = True 
        
        res = []
        vis2 = collections.defaultdict(bool)
        for x in nums2:
            if vis1[x]:
                if vis2[x] == False:
                    res.append(x)
                    vis2[x] = True 
        return res

题目3:202. 快乐数

C++代码如下,

class Solution {
public:
    bool isHappy(int n) {
        set<int> vis;
        while (n != 1 && vis.count(n) == 0) { //n要么为1,要么无限循环
            vis.insert(n);
            int t = 0;
            while (n > 0) {
                t += (n % 10) * (n % 10);
                n /= 10;
            }
            n = t; //更新
        }
        //cout << "n = " << n << endl;
        return n == 1;
    }
};

python3代码如下,

class Solution:
    def isHappy(self, n: int) -> bool:
        vis = set()
        while n != 1 and (n not in vis):
            vis.add(n)
            x = 0
            while n > 0:
                x += int((n % 10) * (n % 10))
                n //= 10
            n = x 
        return n == 1

题目4:1. 两数之和

C++代码如下,

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int, int> map_val_idx; //一边加入一边查询
        for (int i = 0; i < nums.size(); ++i) {
            int x = nums[i];
            int y = target - x;
            if (map_val_idx.count(y) != 0) {
                return {i, map_val_idx[y]};
            } 
            map_val_idx[x] = i;
        }
        return {-1,-1};
    }
};

python3代码如下,

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        map_val_idx = collections.defaultdict(int)
        for i in range(len(nums)):
            x = nums[i]
            y = target - x 
            if y in map_val_idx:
                return [i, map_val_idx[y]]
            map_val_idx[x] = i 
        return [-1,-1]

题目5:454. 四数相加 II

C++代码如下,

class Solution {
public:
    int fourSumCount(vector<int>& nums1, vector<int>& nums2, vector<int>& nums3, vector<int>& nums4) {
        int n = nums1.size();
        int res = 0;
        
        unordered_map<int, int> cnt;
        for (int i = 0; i < n; ++i) {
            int a = nums1[i];
            for (int j = 0; j < n; ++j) {
                int b = nums2[j];
                cnt[a+b]++;
            }
        }

        for (int i = 0; i < n; ++i) {
            int a = nums3[i];
            for (int j = 0; j < n; ++j) {
                int b = nums4[j];
                res += cnt[-a-b];
            }
        }

        return res;
    }
};

python3代码如下,

class Solution:
    def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
        cnt = collections.defaultdict(int)
        for a in nums1:
            for b in nums2:
                cnt[a+b] += 1
        
        res = 0
        for a in nums3:
            for b in nums4:
                res += cnt[-a-b]
        return res

题目6:383. 赎金信

C++代码如下,

class Solution {
public:
    bool canConstruct(string ransomNote, string magazine) {
        vector<int> cnt1(26, 0);
        vector<int> cnt2(26, 0);
        for (auto c : ransomNote) cnt1[c-'a']++;
        for (auto c : magazine) cnt2[c-'a']++;

        for (int i = 0; i < 26; ++i) {
            if (cnt1[i] > cnt2[i]) return false;
        }
        return true;
    }
};

python3代码如下,

class Solution:
    def canConstruct(self, ransomNote: str, magazine: str) -> bool:
        cnt1 = [0] * 26
        cnt2 = [0] * 26
        for c in ransomNote:
            cnt1[ord(c)-ord('a')] += 1
        for c in magazine:
            cnt2[ord(c)-ord('a')] += 1

        for i in range(26):
            if cnt1[i] > cnt2[i]:
                return False 
        return True

题目7:15. 三数之和

以下解法的时间复杂度过高,后续更正

C++代码如下,

//注意nums[i],nums[j],nums[k]去重
class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        map<int, int> map_val_cnt;
        for (auto x : nums) map_val_cnt[x]++;

        vector<int> vals;
        for (auto [k, v] : map_val_cnt) vals.emplace_back(k);

        set<int> vis;
        for (auto x : vals) vis.insert(x);

        int n = vals.size();
        set<vector<int>> ans;
        for (int i = 0; i < n; ++i) {
            int a = vals[i];
            for (int j = 0; j < n; ++j) {
                int b = vals[j];
                int c = 0 - a - b;
                if (vis.count(c) != 0) {
                    unordered_map<int,int> curr_cnt;
                    curr_cnt[a]++;
                    curr_cnt[b]++;
                    curr_cnt[c]++;
                    if (curr_cnt[a] <= map_val_cnt[a] && 
                    curr_cnt[b] <= map_val_cnt[b] &&
                    curr_cnt[c] <= map_val_cnt[c]) {
                        vector<int> t = {a, b, c};
                        sort(t.begin(), t.end());
                        ans.insert(t);
                    }
                }
            }
        }

        vector<vector<int>> res(ans.begin(), ans.end());
        return res;
    }
};

python3代码如下,

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        map_val_cnt = collections.defaultdict(int)
        for x in nums:
            map_val_cnt[x] += 1
        
        vals = []
        for val in map_val_cnt:
            vals.append(val)

        vis = set()
        for val in vals:
            vis.add(val)
        
        ans = set()
        n = len(vals)
        for i in range(n):
            a = vals[i]
            for j in range(n):
                b = vals[j]
                c = 0 - a - b
                if c in vis:
                    curr_cnt = collections.defaultdict(int)
                    curr_cnt[a] += 1
                    curr_cnt[b] += 1
                    curr_cnt[c] += 1

                    if curr_cnt[a] <= map_val_cnt[a] and \
                    curr_cnt[b] <= map_val_cnt[b] and \
                    curr_cnt[c] <= map_val_cnt[c]:
                        t = [a, b, c]
                        t.sort()
                        ans.add(tuple(t))
        ans = list(ans)
        ans = [list(x) for x in ans]
        return ans

题目8:18. 四数之和

以下解法的时间复杂度过高,后续更正

C++代码如下,

typedef long long LL;

class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        map<int, int> map_val_cnt;
        for (auto x : nums) map_val_cnt[x] += 1;

        vector<int> vals;
        set<int> vis;
        for (auto [k, v] : map_val_cnt) {
            vals.emplace_back(k);
            vis.insert(k);
        }

        set<vector<int>> ans;
        int n = vals.size();
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < n; ++j) {
                for (int k = 0; k < n; ++k) {
                    int a = vals[i];
                    int b = vals[j];
                    int c = vals[k];
                    LL t = (LL)target - a - b - c;
                    
                    if (t > INT_MAX || t < INT_MIN) { //如果t超出了整型范围,那么vis.count(d)一定为0
                        continue;
                    }

                    int d = (LL)target - a - b - c;

                    if (vis.count(d) != 0) { 
                        unordered_map<int,int> curr_cnt;
                        curr_cnt[a]++;
                        curr_cnt[b]++;
                        curr_cnt[c]++;
                        curr_cnt[d]++;
                        if (curr_cnt[a] <= map_val_cnt[a] && curr_cnt[b] <= map_val_cnt[b] &&
                        curr_cnt[c] <= map_val_cnt[c] && curr_cnt[d] <= map_val_cnt[d]) {
                            vector<int> t = {a, b, c, d};
                            sort(t.begin(), t.end());
                            ans.insert(t);
                        }
                    }
                }
            }
        }

        vector<vector<int>> res(ans.begin(), ans.end());
        return res;
    }
};

python3代码如下,

class Solution:
    def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
        map_val_cnt = collections.defaultdict(int)
        for x in nums:
            map_val_cnt[x] += 1
        
        vals = []
        vis = set()
        for x in map_val_cnt:
            vals.append(x)
            vis.add(x)
        
        ans = set()
        n = len(vals)
        for i in range(n):
            for j in range(n):
                for k in range(n):
                    a = vals[i]
                    b = vals[j]
                    c = vals[k]
                    d = target - a - b - c 
                    if d in vis:
                        curr_cnt = collections.defaultdict(int)
                        curr_cnt[a] += 1
                        curr_cnt[b] += 1
                        curr_cnt[c] += 1
                        curr_cnt[d] += 1
                        if curr_cnt[a] <= map_val_cnt[a] and curr_cnt[b] <= map_val_cnt[b] and \
                        curr_cnt[c] <= map_val_cnt[c] and curr_cnt[d] <= map_val_cnt[d]:
                            t = [a, b, c, d]
                            t.sort()
                            t = tuple(t)
                            ans.add(t)
        res = list(ans)
        res = [list(x) for x in res]
        return res

3 参考

代码随想录官网

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/605704.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

Python中的函数定义(def)详解

Python中的函数定义&#xff08;def&#xff09;详解 在编程语言中&#xff0c;函数是组织代码的一种方式&#xff0c;它们可以帮助我们将复杂的程序拆分为简单、易管理的部分。在Python中&#xff0c;函数的定义使用def关键字。 什么是函数&#xff1f; 函数是一段完成特定…

虚拟串口调试(Windows)

在单片机和嵌入式设备开发过程中&#xff0c;我们有时需要对程序的串口进行调试&#xff0c;但是身边又恰好没有硬件设备&#xff0c;此时&#xff0c;我们可以通过虚拟串口来实现模拟本地端口&#xff0c;方便调试。 软件安装 VSPD虚拟串口工具 下载VSPD软件&#xff1a;百…

django和vue开发的前后端分离网站怎么部署到服务器上,django和vue前后端分离网站怎么通过宝塔部署

提示&#xff1a;如果看完全部教程后仍然部署不成功&#xff0c;可以联系作者 一、提前准备 想要把django vue 前后端分离网站部署到服务器上&#xff0c;有一些提前准备的东西 1、备案域名&#xff08;域名必须备案&#xff09; 这里需要解析两个域名&#xff0c;一个前端&…

【数据结构|C语言版】栈和队列

前言1. 栈1.1 栈的概念和性质1.2 顺序栈1.3 链栈1.4 共享栈 2. 队列2.1 队列的概念和性质2.2 循环队列2.3 链式队列2.4 双端队列 3. 例题精选3.1 有效的括号3.2 用队列实现栈2.4 用栈实现队列3.4 设计循环队列3.5 参考答案 结语 #include<GUIQU.h> int main { 上期回顾: …

浏览器控制台console常用命令小结

chrome调试工具的Console对象相信很多人使用过&#xff0c;熟练的Web开发人员会经常使用 console.log() 在其代码中打印消息和调试问题&#xff0c;实际上还有很多很有用的功能和技巧&#xff0c;善用之可以极大提高Web开发&#xff0c;网站调优的效率&#xff01; 这里我们总结…

Ansible---Playbook剧本

文章目录 Playbook案例1 Playbook剧本基本用法案例2 Playbook剧本定义、引用变量案例3.when条件判断迭代剧本Roles 模块 Playbook Tasks&#xff1a;任务是 Playbooks 的核心&#xff0c;它们是 Playbook 中的一项指令&#xff0c;告诉 Ansible 在远程主机上执行什么操作。每个…

kubectl_进阶_安全

安全 在前面的学习中&#xff0c;我们知道对于资源对象的操作都是通过 APIServer 进行的&#xff0c;那么集群是怎样知道我们的请求就是合法的请求呢&#xff1f; 这就涉及到k8s的安全相关的知识了。 1. API对象 Kubernetes有一个很基本的特性就是它的所有资源对象都是模型…

pdf2htmlEX:pdf 转 html,医学指南精细化处理第一步

pdf2htmlEX&#xff1a;pdf 转 html&#xff0c;医学指南精细化处理第一步 单文件转换多文件转换 代码&#xff1a;https://github.com/coolwanglu/pdf2htmlEX 拉取pdf2htmlEX 的 Docker&#xff1a; docker pull bwits/pdf2htmlex # 拉取 bwits/pdf2htmlex不用进入容器&…

统信UOS 1070桌面操作系统如何备份及恢复全盘数据

原文链接&#xff1a;统信UOS 1070桌面操作系统如何备份及恢复全盘数据 Hello&#xff0c;大家好啊&#xff01;数据备份和还原对于保护我们的重要信息至关重要&#xff0c;尤其是当系统遭遇意外时&#xff0c;能够快速恢复到正常状态。今天&#xff0c;我将介绍如何在统信UOS …

树莓派配置双网卡分别为AD HOC和AP模式

树莓派配置双网卡分别为AD HOC和AP模式 需求说明&#xff1a;为了实现分级网络管理&#xff0c;将多个无人机分簇&#xff0c;簇间使用AD HOC进行无中心自组织的网络&#xff0c;簇内使用AP-AC模式进行中心化网络。因此&#xff0c;需要配置一台设备&#xff0c;同时完成AD HOC…

设计模式——行为型模式——策略模式(含实际业务使用示例、可拷贝直接运行)

目录 策略模式 定义 组成和UML图 代码示例 实际业务场景下策略模式的使用 策略模式优缺点 使用场景 JDK中使用策略模式示例 参考文档 策略模式 定义 策略模式定义了一系列算法&#xff0c;并将每个算法封装起来&#xff0c;使它们可以相互替换&#xff0c;且算法的变化…

【微信小程序开发】微信小程序、大前端之flex布局方式详细解析

✨✨ 欢迎大家来到景天科技苑✨✨ &#x1f388;&#x1f388; 养成好习惯&#xff0c;先赞后看哦~&#x1f388;&#x1f388; &#x1f3c6; 作者简介&#xff1a;景天科技苑 &#x1f3c6;《头衔》&#xff1a;大厂架构师&#xff0c;华为云开发者社区专家博主&#xff0c;…

液晶高抗干扰驱动LCD段码屏驱动芯片VK2C22抗干扰系列瓦斯表段码LCD液晶驱动芯片

VK2C22是一个点阵式存储映射的LCD驱动器&#xff0c;可支持最大176点&#xff08;44SEGx4COM&#xff09;的LCD屏。单片机可通过I2C接口配置显示参数和读写显示数据&#xff0c;也可通过指令进入省电模式。其高抗干扰&#xff0c;低功耗的特性适用于水电气表以及工控仪表类产品…

简单几步解决Windows 10播放视频提示安装HEVC扩展

相信有不少人都遇到过以下的问题&#xff0c;废话不多说&#xff0c;直接上干货&#xff01; 1.下载插件 免费地址链接: 点击下载 2.安装插件 如图所示&#xff0c;在下载的目录路径里&#xff0c; 1.按住键盘 SHIFT&#xff0c;点击鼠标右键&#xff0c;选择在此处打开Powe…

4WRPH系列比例阀外置放大器

控制4WRPH6或4WRPH10比例伺服阀放大器适用于驱动带非线性曲线的直动式比例伺服电磁阀&#xff0c;模拟量控制电器放大器模块式的放大器用于安装在机柜内35mm卡轨架上&#xff0c;输出级带电气反馈用于闭环控制。使能输入功能可控制放大器输出开或关&#xff0c;带斜坡时间发生器…

const成员函数、cout/cin和重载运算符<<、>>、

目录 一、为什么cout&#xff0c;cin可以自动识别类型&#xff1f; 二、留提取运算符重载&#xff08;<<&#xff09; 三、留插入运算符重载&#xff08;>>&#xff09; 四、对上述的总结&#xff1a; 五、const成员 成员函数原则&#xff1a; 六、默认成员函…

Object类

Object类 概念&#xff1a;Object类是所有类的父类&#xff0c;也就是说任何一个类在定义时候如果没有明确的指定继承一个父类的话&#xff0c;那么它就都默认继承Object类&#xff0c;因此Object类被称为所有类的父类&#xff0c;也叫做基类/超类。 常用方法 方法类型描述eq…

Python实战开发及案例分析(12)—— 模拟退火算法

模拟退火算法&#xff08;Simulated Annealing&#xff09;是一种概率搜索算法&#xff0c;源自于金属退火过程。在金属退火中&#xff0c;通过缓慢降低温度&#xff0c;金属内部的原子能够从高能态逐步达到较低能态。模拟退火算法利用类似的原理&#xff0c;通过随机搜索和概率…

Samtec连接器应用科普 | 连接智能工厂中的AI

【摘要/前言】 本文是系列的第一部分&#xff0c;我们将探讨人工智能在工业领域的作用。 人工智能&#xff08;AI&#xff09;的话题最近成为头条新闻&#xff0c;因为最新一代基于云的人工智能工具有望为机器的力量带来重大飞跃。在所有关于人工智能将如何影响我们的讨论中&…

Android内核之Binder消息处理:binder_transaction用法实例(七十三)

简介&#xff1a; CSDN博客专家&#xff0c;专注Android/Linux系统&#xff0c;分享多mic语音方案、音视频、编解码等技术&#xff0c;与大家一起成长&#xff01; 优质专栏&#xff1a;Audio工程师进阶系列【原创干货持续更新中……】&#x1f680; 优质专栏&#xff1a;多媒…
最新文章