-
Notifications
You must be signed in to change notification settings - Fork 0
/
706_design_hashmap.rb
93 lines (77 loc) · 1.52 KB
/
706_design_hashmap.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# frozen_string_literal: true
# https://leetcode.com/problems/design-hashmap/
class MyHashMap
# Init
def initialize
@entries = ::Array.new(500, nil)
end
# @param {Integer} key
# @param {Integer} value
def put(key, value)
i = index_for(key.hash, @entries.length)
e = @entries[i]
if e.nil?
@entries[i] = ::Entry.new(key, value)
elsif e.key == key
e.value = value
else
p = e
until e.nil?
if e.key == key
e.value = value
break
end
p = e
e = e.next
end
p&.next = ::Entry.new(key, value) if e.nil?
end
end
# @param {Integer} key
# @return {Integer}
def get(key)
i = index_for(key.hash, @entries.length)
e = @entries[i]
unless e.nil?
until e.nil?
return e.value if e.key == key
e = e.next
end
end
-1
end
# @param {Integer} key
def remove(key)
i = index_for(key.hash, @entries.length)
e = @entries[i]
return if e.nil?
if e.key == key
@entries[i] = e.next
else
p = e
e = e.next
until e.nil?
p.next = e.next if e.key == key
p = e
e = e.next
end
end
end
private
# @param {Integer} hash
# @param {Integer} length
def index_for(hash, length)
hash & (length - 1)
end
end
# Entry
class Entry
# @param {Integer} key
# @param {Integer} value
def initialize(key, value)
@key = key
@value = value
@next = nil
end
attr_accessor :key, :value, :next
end