数据结构5 哈希表(Hash Table)

本文详细介绍了哈希表的概念,包括哈希碰撞及其解决策略,如链表法。阐述了Python和Java中创建、添加、修改、删除和查找哈希表元素的操作,并提供了相关例题展示哈希表在实际问题中的应用,如查找重复元素和寻找字符串差异。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. 键值对 key : value
  2. 哈希碰撞:两个不同的key通过同一个hash函数得到相同的内存地址
    4通过哈希函数解析出的地址也是1,冲突了。
    解决方法:
    链表法, 在后面通过链表加入内存地址相同的值。
  3. 复杂度
  • 访问: 没有这个方法
  • 搜索:O(1), 如果有hash碰撞的情况下,就不是O(1)了,为O(K), K为碰撞元素的个数
  • 插入: O(1)
  • 删除: O(1)
  1. Python常用操作:
  • 创建哈希表:
# 使用数组创建hash
hashTable = ['']x4
# 使用字典创建hash
mapping = {}
  • 添加元素:
hashTable[1] = 'hanmeimei'
hashTable[2] = 'lihua'
hashTable[3] = '233'
mapping[1] = 'hanmeimei'
mapping[2] = 'lihua'
mapping[3] = '233'
  • 修改元素:
hashTable[1] = 'unspoken'
mapping[1] = 'asdf'
  • 删除元素:
hashTable[3] = ''
mapping.pop(1)   # 删除key=1的值
# 或者使用del
del mapping[1]
  • 获取元素:
hashTable[3]
mapping[2]
  • 检查key是否存在:
3 in mapping
  • 哈希表的长度:
len(mapping)
  • 哈希表是否还有元素:
len(mapping) == 0
  1. java常用操作:
//创建哈希表
java.lang.String[] hashTable = new java.lang.String[4];

HashMap<Integer, java.lang.String> map = new HashMap<>();

//添加元素
hashTable[1] = "xiayi";
hashTable[2] = "dan";
hashTable[3] = "lumos";
map.put(1,"xiayi");
map.put(2,"dan");
map.put(3,"lumos");

//修改元素
hashTable[3] = "raven";
map.put(1,"raven");

//删除元素
hashTable[3] = "";
map.remove(1);

//获取元素
java.lang.String temp = hashTable[2];
map.get(3);

//检查key是否存在
map.containsKey(3);

//长度
map.size();

//是否还有元素
map.isEmpty();

  1. 例题
    在这里插入图片描述
class Solution {
    public boolean containsDuplicate(int[] nums) {
        HashMap<Integer,Integer> map = new HashMap<>();
        for(int i = 0;i<nums.length;i++){
            if(map.containsKey(nums[i]) == false){
                map.put(nums[i],1);
            }
            else{
                return true;
            }
        }
        return false;
    }
}
class Solution:
    def containsDuplicate(self, nums: List[int]) -> bool:
        dict =  {}
        for i in nums:
            if i not in dict:
                dict[i] = 1
            else:
                return True
        return False

在这里插入图片描述

class Solution:
    def findTheDifference(self, s: str, t: str) -> str:
        dict = {}
        for i in t:
            if i in dict:
                dict[i] += 1
            else:
                dict[i] = 1
        #print(dict)
        for i in s:
            if i in dict:
                dict[i] -= 1
        #print(dict)
        for i in dict:
            if dict.get(i) == 1:
                return i
class Solution {
    public char findTheDifference(String s, String t) {
        int res = 0;
        for (char c:s.toCharArray()){
            res^=c;
        }
        for (char c:t.toCharArray()){
            res^=c;
        }
        return (char)res;
    }
}

在这里插入图片描述

class Solution {
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        int[] res = new int[nums1.length];
        Stack<Integer> stack = new Stack<>();
        for(int i = 0;i<nums2.length;i++){
            stack.push(i);
        }
        for (int i = 0;i<nums1.length;i++){
            boolean isFound = false;
            int max = -1;
            int count = 0;
            Stack<Integer> temp = new Stack<>();
            while(stack.size() != 0 && isFound == false){
                int top = stack.pop();
                if (top > nums1[i]){
                    max = top;
                }
                else if(top == nums1[i]){
                    isFound = true;
                }
                temp.push(top);
            }
            res[count] = max;
            count++;
            while(temp.size()!=0){
                stack.push(temp.pop());
            }
        }
        return res;
    }
}
class Solution:
    def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
        res = []
        stack = []
        for i in nums2:
            stack.append(i)
        for num in nums1:
            temp = []
            isFound = False
            max = -1
            while(len(stack)!=0 and isFound == False):
                top = stack.pop()
                if top > num:
                    max = top
                elif top == num:
                    isFound = True
                temp.append(top)
            res.append(max)
            while(len(temp)!=0):
                stack.append(temp.pop())
        return res
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值