Day.14 Hash map II

今天要把上一篇讲的hash map写成code!

struct

type Node struct {
	key  string
	val  int
	next *Node
}

type HashMap struct {
	bucket [4]*Node
	len    int
}

hash function

func (h *HashMap) hashKey(key string) int {
	// 先把string转成 ASCII code再 % 桶子的大小
	return int(key[0]) % len(h.bucket)
}

get

func (h *HashMap) Get(key string) (val int, exist bool) {
	node := h.bucket[h.hashKey(key)]
	// 找不到
	if node == nil {
		return 0, false
	}

	// 找到同一样的key 再回传
	for node != nil {
		if node.key == key {
			return node.val, true
		}

		node = node.next
	}

	return 0, false
}

set

func (h *HashMap) Set(key string, val int) {
	hashkey := h.hashKey(key)
	if h.bucket[hashkey] == nil {
		h.bucket[hashkey] = &Node{
			key: key,
			val: val,
		}
		h.len++

		return
	}

	// 寻找是否有一样的key的节点,如果有就update
	node := h.bucket[hashkey]
	for node != nil {
		if node.key == key {
			node.val = val
			return
		}

		node = node.next
	}

	// 没找到一样key的
	// 把新的节点放在第一个位置
	h.bucket[hashkey] = &Node{
		key:  key,
		val:  val,
		next: h.bucket[hashkey],
	}
	h.len++
}

delete

func (h *HashMap) Delete(key string) {
	node := h.bucket[h.hashKey(key)]
	// 找不到
	if node == nil {
		return
	}

	// 删的是第一个节点
	if node.key == key {
		h.bucket[h.hashKey(key)] = nil
		h.len--
		return
	}

	// 寻找节点
	prev := node
	node = node.next
	for node != nil {
		if node.key == key {
			// 删除
			prev.next = node.next
			h.len--
			return
		}

		prev = node
		node = node.next
	}
}

明天来解leetcode!


<<:  [Day8]什麽是乙太坊?

>>:  Day 7: LeetCode 485. Max Consecutive Ones

[Day 29] LeetCode - 242 Valid Anagram

本篇同步发布於Blog:[解题] LeetCode - 242 Valid Anagram 平台: ...

证书颁发机构(CA)-Web服务器证书格式

-网站WentzWu.com的X.509证书样本 因为如今在实践中很少使用正斜杠“ /”作为分隔符...

Day16,Domain&自签凭证

正文 以前有透过Freenom注册了一个边缘网域,这次就设定了一个homelab domain,将A...

[DAY 29] 复刻 Rails - View 威力加强版 - 1

其实我们的 Mavericks 已经做得差不多了,但就是那个 View 总觉得还可以再更好,如果仔细...

[Day14] 动画篇 - 伤害动画

从Sprite_Damage开始 写一个方法 接着是Sprite_Character 在Action...