Leetcode[217, 136, 349, 202] HashTable 小专题 1 HashSet

亚麻 OA 2019 题目 Most Common Word Prison Cells After N Days K Closest Points to Origin Reorder Log Files Partition Labels Min Cost to Add New Roads Min distance to remove the obstacle Roll Dice Min Cost to Con... 阅读详情

Hash Table is a data structure which organizes data using hash functions in order to support quick insertion and search. In this article, we will take a look at the principle of the hash table.

一 自己定义一个HashSet的基本操作

MyHashSet hashSet = new MyHashSet();
hashSet.add(1);         
hashSet.add(2);         
hashSet.contains(1);    // returns true
hashSet.contains(3);    // returns false (not found)
hashSet.add(2);          
hashSet.contains(2);    // returns true
hashSet.remove(2);          
hashSet.contains(2);    // returns false (already removed)

代码

class MyHashSet {
    private final int MAX_LEN = 100000; // the amount of buckets
    private List<Integer>[] set;      // hash set implemented by array

    /** Initialize your data structure here. */
    public MyHashSet() {
        set = (List<Integer>[])new ArrayList[MAX_LEN];
    }
    /** Returns the corresponding bucket index. */
    private int getIndex(int key) {
        return key % MAX_LEN;
    }
    
    /** Search the key in a specific bucket. Returns -1 if the key does not existed. */
    private int getPos(int key, int index) {
        // Each bucket contains a list.
        List<Integer> temp = set[index];
        if (temp == null) {
            return -1;
        }
        // Iterate all the elements in the bucket to find the target key.
        for (int i = 0; i < temp.size(); ++i) {
            if (temp.get(i) == key) {
                return i;
            }
        }
        return -1;
    }
    public void add(int key) {
        int index = getIndex(key);
        int pos = getPos(key, index);
        if (pos < 0) {
            // Add new key if key does not exist.
            if (set[index] == null) {
                set[index] = new ArrayList<Integer>();
            }
            set[index].add(key);
        }
    }
    
    public void remove(int key) {
        int index = getIndex(key);
        int pos = getPos(key, index);
        if (pos >= 0) {
            // Remove the key if key exists.
            set[index].remove(pos);
        }
    }
    
    /** Returns true if this set did not already contain the specified element */
    public boolean contains(int key) {
        int index = getIndex(key);
        int pos = getPos(key, index);
        return pos >= 0;
    }
}

    

/**
 * Your MyHashSet object will be instantiated and called as such:
 * MyHashSet obj = new MyHashSet();
 * obj.add(key);
 * obj.remove(key);
 * boolean param_3 = obj.contains(key);
 */

The Principle of Built-in Hash Table


The typical design of built-in hash table is:

  1.  The key value can be any hashable type. And a value which belongs to a hashable type will have a hashcode. This code will be used in the mapping function to get the bucket index.
  2.  Each bucket contains an array to store all the values in the same bucket initially.
  3.  If there are too many values in the same bucket, these values will be maintained in a height-balanced binary search tree instead.

The average time complexity of both insertion and search is still O(1). And the time complexity in the worst case is O(logN) for both insertion and search by using height-balanced BST. It is a trade-off between insertion and search.

 

二 Java HashSet的用法

// "static void main" must be defined in a public class.
public class Main {
    public static void main(String[] args) {
        // 1. initialize the hash set
        Set<Integer> hashSet = new HashSet<>();     
        // 2. add a new key
        hashSet.add(3);
        hashSet.add(2);
        hashSet.add(1);
        // 3. remove the key
        hashSet.remove(2);        
        // 4. check if the key is in the hash set
        if (!hashSet.contains(2)) {
            System.out.println("Key 2 is not in the hash set.");
        }
        // 5. get the size of the hash set
        System.out.println("The size of has set is: " + hashSet.size());     
        // 6. iterate the hash set
        for (Integer i : hashSet) {
            System.out.print(i + " ");
        }
        System.out.println("are in the hash set.");
        // 7. clear the hash set
        hashSet.clear();
        // 8. check if the hash set is empty
        if (hashSet.isEmpty()) {
            System.out.println("hash set is empty now!");
        }
    }
}

三 例题:

217 Contains Duplicate

Given an array of integers, find if the array contains any duplicates.

Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.

Example 1:

Input: [1,2,3,1]
Output: true

Example 2:

Input: [1,2,3,4]
Output: false

Approach #1 HashSet 我的解法

class Solution {
    public  boolean containsDuplicate(int[] nums) {
		 Set<Integer> set = new HashSet<Integer>();
		 for(Integer i : nums){
			 if(set.contains(i))
				 return true; 
             else
                 set.add(i);
         }   
		 return false;
	 }
}

Complexity Analysis

  • Time complexity : O(n). We do search() and insert() for n times and each operation takes constant time.

  • Space complexity : O(n). The space used by a hash table is linear with the number of elements in it.

136 Single Number

Given a non-empty array of integers, every element appears twice except for one. Find that single one.

Note:

Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

Example 1:

Input: [2,2,1]
Output: 1

Example 2:

Input: [4,1,2,1,2]
Output: 4

Approach #1 Hash Set 我的解法

class Solution {
    public int singleNumber(int[] nums) {
        Set<Integer> hashSet = new HashSet<>();
        for(int n: nums){
            if(hashSet.contains(n))
                hashSet.remove(n);
            else
                hashSet.add(n);
        }
        int ans = 0;
        for(Integer i: hashSet){
            ans = i;
        }
        return ans;
    }
}

Complexity Analysis

  • Time complexity : O(n \cdot 1) = O(n)O(n⋅1)=O(n). Time complexity of for loop is O(n)O(n). Time complexity of hash table(dictionary in python) operation pop is O(1)O(1).

  • Space complexity : O(n)O(n). The space required by hash\_tablehash_table is equal to the number of elements in \text{nums}nums. 

349. Intersection of Two Arrays

Given two arrays, write a function to compute their intersection.

Example 1:

Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2]

Example 2:

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [9,4]

Note:

  • Each element in the result must be unique.
  • The result can be in any order.

我的解法

class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        Set<Integer> hashSet = new HashSet<>();
        Set<Integer> hs1 = new HashSet<>();
        Set<Integer> hs2 = new HashSet<>();
        
        for(int a: nums1) hs1.add(a);
        for(int b: nums2) hs2.add(b);
        for(int n: nums1){
            if(hs1.contains(n)&&hs2.contains(n)){
                hashSet.add(n);
            }
        }
        int[] ans = new int[hashSet.size()];
        int i = 0;
        for(Integer h: hashSet) ans[i++] = h;
        return ans;
    }
}

202. Happy Number

Write an algorithm to determine if a number is "happy".

A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.

Example: 

Input: 19
Output: true
Explanation: 
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
class Solution {
    public boolean isHappy(int n) {
    Set<Integer> inLoop = new HashSet<Integer>();
    int squareSum,remain;
	while (inLoop.add(n)) {
		squareSum = 0;
		while (n > 0) {
		    remain = n%10;
			squareSum += remain*remain;
			n /= 10;
		}
		if (squareSum == 1)
			return true;
		else
			n = squareSum;

	}
	return false;

    }
}

 

Leetcode 250. Count Univalue Subtrees 谷歌面试, Java解法详解 这是一道谷歌会考的题目 Given a binary tree, count the number of uni-value subtrees. A Uni-value subtree means all nodes of the subtree have the same value. Example : Input: root = [5,1,5,5,5,null,5] ... 阅读详情

相关推荐

VLOOKUP_fixed.py

VLOOKUP_fixed.py

Leetcode 1086. High Five Java 解法

先吐槽一下这个难度,咋也不能是easy啊,和其他easy的不在一个量级。 Given a list of scores of different students, return the average score of each student'stop five scoresinthe order of each student's id. Each entryitems[i]h...

YuanTheCoder的博客 1473

YOLO26算法心电图十二导联目标检测+训练好的模型+368张数据集+pyqt可视化界面.zip

附训练好的 YOLO 权重与 PyQt 可视化检测界面,页面底部含可视化效果预览,毕设/课设开箱即用。 【数据集概况】 · 检测类别(中文):[导联I(I), 导联II(II), 导联III(III), 胸导联V1(V1), 胸导联V2(V2), 胸导联V3(V3), 胸导联V4(V4), 胸导联V5(V5), 胸导联V6(V6), 加压肢体导联aVF(aVF), 加压肢体导联aVL(aVL), 加压肢体导联aVR(aVR)] · 训练集:313 张 · 验证集:37 张 · 测试集:18 张 · 总计:368 张 该数据集聚焦于临床心电图信号的精准识别与定位,其核心检测目标为标准12导联心电图中的各个独立导联波形区域,涵盖肢体导联(I、II、III)与加压肢体导联(aVR、aVL、aVF),以及胸前导联(V1至V6),适用于心电图自动分析系统中对各导联位置的快速准确标注与分类。数据采集场景真实还原了医院心电图室或急诊监护环境下的标准心电图记录纸,波形清晰、基线稳定,具有高度临床参考价值。... 【训练曲线与评估图】 【模型训练配置】 参数 | 值 模型 | yolo26n 训练轮数 | 100 epochs 输入尺寸 | 640x640 批次大小 | 24 优化器 | auto 初始学习率 | 0.01 训练设备 【关键指标汇总】 训练了 57 个 epoch,最终轮指标: 指标 | 数值 mAP50 | **0.9708** mAP50-95 | 0.6344 Precision | 0.8990 Recall | 0.9191 train/box_loss | 1.2231 train/cls_loss | 0.9703 val/box_loss | 1.2779 val/cls_loss | 0.... 使用场景:毕业设计、课程设计、深度学习入门、工业场景落地验证。

Leetcode 1051. Height Checker, Java解法

Students are asked to stand in non-decreasing order of heights for an annual photo. Return the minimum number of students not standing in the right positions. (This is the number of students that mu...

YuanTheCoder的博客 649

企业级AI助手平台 开箱即用的全栈AI平台,支持多智能体协同、Supervisor模式编排、多种决策模式、RAG技术和流程编排能力 支持多厂商大模型统一接入与管理,安全可控的企业知识库与高精度检索优化

企业级AI应用开发框架,支持多厂商大模型统一接入与管理,安全可控的企业知识库与高精度检索优化能力,提供可视化流程编排、自主决策智能体与多智能体协同调度,兼容主流 Agent Skill 协议,帮助企业与开发者零门槛快速构建安全、高效、可落地的AI智能体应用与行业解决方案。

基于动态窗口法DWA的机器人路径规划研究(Matlab代码实现)

内容概要:本文系统研究了基于动态窗口法(DWA)的机器人局部路径规划算法,深入剖析其在动态环境中实现自主避障与实时轨迹优化的核心机制。文章详细阐述了DWA算法的速度空间采样策略、轨迹预测模型、动力学约束处理及多目标代价函数的设计原理,并通过构建完整的Matlab仿真框架验证算法有效性。结合典型场景的仿真实验,展示了机器人在复杂障碍物环境下如何实时生成安全、平滑且符合运动学约束的最优路径,充分体现了DWA在移动机器人导航中的实用性与鲁棒性。; 适合人群:具备机器人运动规划基础知识和Matlab编程能力,从事智能移动机器人、自动驾驶或服务机器人研发的研究生、科研人员及工程技术人员。; 使用场景及目标:①深入理解DWA算法的理论基础与实现细节;②掌握机器人局部路径规划的仿真实现方法;③为实际机器人系统的导航模块开发提供可复用的算法原型与代码参考;④作为进一步研究高级导航算法(如TEB、MPC)的技术基础。; 阅读建议:建议结合提供的Matlab代码逐模块分析与调试,重点关注速度采样、轨迹积分、障碍物距离计算及代价评估等关键环节,通过调整参数在不同地图环境中进行对比实验,以深刻把握算法性能与参数之间的关系,进而提升对实时路径规划系统设计的理解与应用能力。

Leetcode 1108. Defanging an IP Address, Java解法

Given a valid (IPv4) IPaddress, return a defanged version of that IP address. AdefangedIP addressreplaces every period"."with"[.]". Example 1: Input: address = "1.1.1.1" Output: "1[.]1[....

YuanTheCoder的博客 574

【轴承故障诊断】用于轴承故障诊断的集中时频分析研究(Matlab代码实现)

内容概要:本文系统研究了用于轴承故障诊断的集中时频分析技术,重点解决了传统时频分析方法在处理非平稳信号时存在的能量分散与分辨率不足等问题。通过引入集中时频分析方法,能够有效聚焦信号能量,精确提取轴承故障特征频率,提升故障识别的准确性与时效性。文章详细阐述了该方法的理论基础,并结合仿真信号与实际实验数据验证其优越性能,同时提供了完整的Matlab代码实现流程,涵盖信号预处理、时频变换、参数优化及结果可视化等环节,便于读者复现与拓展应用。; 适合人群:具备一定信号处理理论基础和Matlab编程能力的研究生、科研人员,以及从事机械设备状态监测、故障诊断与预测性维护工作的工程技术人员。; 使用场景及目标:①应用于电机、风机、齿轮箱等旋转机械的早期轴承故障检测,实现故障预警;②提升工业设备运维系统的智能化水平,支撑预测性维护体系构建;③作为高校或研究机构在信号处理、机械故障诊断等课程中的教学案例与实践素材。; 阅读建议:建议读者结合文中提供的Matlab代码逐段运行与调试,深入理解集中时频分布的生成机制及其关键参数(如核函数选择、平滑窗口大小)对诊断效果的影响,并尝试将其应用于其他类型的机械故障信号分析中,开展对比研究以深化对该方法适用性的认识。

Java中 Queue队列的用法及例子

1. Usage 用法 // "static void main" must be defined in a public class. public class Main { public static void main(String[] args) { // 1. Initialize a queue. Queue<Integer> q...

YuanTheCoder的博客 557

【深度学习】肺结节分割项目实战一:处理数据集

一、LIDC-IDRI数据集简介 官方网站 肺图像数据库协会的图像收集(LIDC-IDRI)包括诊断和带有病变注释标记的肺癌筛查胸部CT。这是一个网络公开的国际资源,用于肺癌检测和诊断的计算机辅助诊断(CAD)方法的开发、培训和评估。 数据集包含1018个病例,每个病例包括来自临床胸部CT扫描的图像和一个相关的XML文件,该文件记录了由四名经验丰富的胸部放射科医生进行的两阶段图像注释过程的结果。在最初的盲读阶段,每个放射科医生独立审查每个CT扫描,并标记出属于三种类型之一的病变(“结节>= 3mm”,

weixin_42182906的博客 1万+

深入解析MOS管电容特性:从基础理论到高频应用

本文深入解析了MOS管的电容特性,从基础物理结构出发,详细拆解了栅氧电容、重叠电容和结电容的成因与影响。文章重点探讨了电容值随工作状态变化的非线性特性,并分析了其在CMOS高频开关电源、射频电路等应用中的关键作用,包括开关损耗、米勒效应、信号完整性挑战以及如何将电容特性转化为可控元件(如MOS变容管)的机遇。最后提供了从选型、仿真到PCB布局的实战设计指南。

weixin_29278805的博客 381

Leetcode 509. Fibonacci Number , Java 解法

TheFibonacci numbers, commonly denotedF(n)form a sequence, called theFibonacci sequence, such that each number is the sum of the two preceding ones, starting from0and1. That is, F(0) = 0, F(...

YuanTheCoder的博客 503

Cursor设置界面汉化保姆级教程:手把手教你修改JS文件实现中文界面(附避坑指南)

本文提供Cursor编辑器设置界面汉化的详细教程,从定位JS文件到安全修改实现中文界面,包含必备工具清单、文件路径指引和常见问题解决方案。通过手把手教学帮助用户轻松完成汉化,提升使用体验,特别适合不熟悉英文界面的开发者。

weixin_29007809的博客 1412

Leetcode 977. Squares of a Sorted Array, Java解法

Given an array of integersAsorted in non-decreasing order,return an array of the squares of each number,also in sorted non-decreasing order. Example 1: Input: [-4,-1,0,3,10] Output: [0,1,9,16,1...

YuanTheCoder的博客 497

Cosmos Transfer2.5多模态AI模型部署与优化实战

多模态AI技术通过融合文本、图像、代码等不同模态数据,实现跨模态理解与生成。其核心原理基于Transformer架构的注意力机制,结合对比学习实现模态对齐。这类技术在智能内容创作、跨模态搜索等领域具有重要价值,尤其适合电商营销图文生成、UI设计转代码等场景。Cosmos Transfer2.5作为先进的多模态模型,支持8192 tokens长文本窗口和混合模态输入,实测推理速度达17.5 samples/s(T4显卡)。部署时需注意FlashAttention优化可提升3倍长文本处理效率,8-bit量化则能

weixin_29038303的博客 280

OCR开发车架号识别vin码识别系统

一、vin码识别车架号识别系统简介   vin码识别车架号识别系统,结合VIN码主机厂数据库及自身多年文字识别经验,针对机动车配置参数等信息的查询及采集业务推出的一款VIN码自动识别产品。   车架号识别vin码识别,主要应用在智能手机IOS与Android两个平台中。前端扫描查询模式,无需联网,只需扫描汽车前挡风玻璃右下角的VIN玛(车架号),即可轻松识别出车辆产地、品牌、车

OCR13512721355的博客 1433

狗家 Online Assessment

License Key Formatting Unique Email Addresses Fruit Into Baskets Odd Even Jump Maximum Area Serving Cake Min Days to Bloom Fill Matrix Compare Strings Largest Subarray Length K Decreasing Sub...

YuanTheCoder的博客 470

嵌入式工程师成长之路(3)——PCB设计

带有目的的学:要知道,PCB板子做出来需要我们给厂家哪些东西,我们设计板子的时候,需要遵循哪些设计规范,防止画好也是块废板子。然后再逐步开始学习画板。

云轩阁 8万+

Leetcode 922. Sort Array By Parity II , Java解法

Given an arrayAof non-negative integers, half of the integers in A are odd, and half of the integers are even. Sort the array so that wheneverA[i]is odd,iis odd; and wheneverA[i]is even,iis...

YuanTheCoder的博客 444

Qt Android MySql 数据库驱动编译(详细图解步骤)

第一步.先介绍下环境搭建: Qt 版本 5.12.11 下载链接 https://download.qt.io/archive/qt/5.12/5.12.11/qt-opensource-linux-x64-5.12.11.run Ubuntu 18.04.6 LTS 下载链接 JDK版本 1.8.0_191 下载链接https://www.oracle.com/java/technologies/downloads/ Android Studio版本 ...

h a 6 6 6 c k 为 你解决复杂难题! 3380

[Dify实战] 做企业内部助手时,最容易被低估的不是提示词,而是权限、状态同步和反馈回写

这篇文章围绕“做企业内部助手时”这个具体问题展开,很多团队做企业内部助手时,最先优化的是提示词,但真正决定系统能不能上线长期跑下去的,往往是权限边界、状态同步和反馈回写闭环。正文会结合Dify拆解节点设计、配置建议和测试样例,补充关键步骤、检查点和常见坑,帮助读者判断第一版该怎么落地,并把经验复用到自己的真实业务场景中。

技术小甜甜:传播可落地技术,帮助个人和企业降低解决真实场景问题的成本 68

Leetcode [141, 142] Linked List Cycle,java解法

141 Linked List Cycle Given a linked list, determine if it has a cycle in it. To represent a cycle in the given linked list, we use an integerposwhich represents the position (0-indexed)in the l...

YuanTheCoder的博客 419

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

Leetcode 1089. Duplicate Zeros, java解法 及Queue的使用

Given a fixed lengtharrayarrof integers, duplicate each occurrence of zero, shifting the remaining elements to the right. Note that elements beyond the length of the original array are not written...

YuanTheCoder的博客 417

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

Leetcode 1002. Find Common Characters, Java 解法

Given an arrayAof strings made only from lowercase letters, return a list of all characters that show up in all strings within the list(including duplicates).For example, if a character occurs 3 ...

YuanTheCoder的博客 385

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

Leetcode 1119. Remove Vowels from a String, Java解法

Given a stringS, remove the vowels'a','e','i','o', and'u'from it, and return the new string. Example 1: Input: "leetcodeisacommunityforcoders" Output: "ltcdscmmntyfrcdrs" Example 2: Inpu...

YuanTheCoder的博客 380

Leetcode 561. Array Partition I, Java解法

Given an array of2nintegers, your task is to group these integers intonpairs of integer, say (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as poss...

YuanTheCoder的博客 368
上一篇: Leetcode 1089. Duplicate Zeros, java解法 及Queue的使用
下一篇: Leetcode [141, 142] Linked List Cycle,java解法
YuanTheCoder
博客等级 码龄9年 2粉丝 34原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值