-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path4_22.rb
More file actions
123 lines (87 loc) · 2.1 KB
/
Copy path4_22.rb
File metadata and controls
123 lines (87 loc) · 2.1 KB
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# @param {Integer[]} nums
# @return {Integer}
def majority_element(nums)
counter_hash = Hash.new(0)
nums.each {|el| counter_hash[el] +=1}
counter_hash.keys.each do |el|
return el if counter_hash[el]> (nums.length/2)
end
end
# O(n)
# Definition for singly-linked list.
# class ListNode
# attr_accessor :val, :next
# def initialize(val)
# @val = val
# @next = nil
# end
# end
# @param {ListNode} head
# @param {Integer} val
# @return {ListNode}
def remove_elements(head, val)
return [] if head && head.val == val && !head.next
current = head
while current
if current.next && current.next.val == val
current.next = current.next.next
else
current = current.next
end
end
head
end
# @param {Integer[]} nums
# @param {Integer} k
# @return {Integer}
def find_kth_largest(nums, k)
nums.sort!
nums[-k]
end
# @param {Integer[]} nums
# @param {Integer} k
# @return {Integer}
class MaxHeap
attr_accessor :array
def initialize()
@array = [null]
end
def get_parent(idx)
(idx/2)
end
def get_left_child(idx)
idx*2
end
def get_right_child(idx)
(idx*2) + 1
end
def sift_up(idx)
return if idx <=1
parent_idx = self.get_parent(idx)
current = self.array[idx]
parent = self.array[parent_idx]
if current > parent
self.array[parent_idx], self.array[idx] = self.array[idx], self.array[parent_idx]
self.sift_up(parent_idx)
end
end
def insert(val)
self.array.push(val)
self.sift_up(self.array.length - 1)
end
def delete_max()
end
def sift_down(idx)
end
end
#becomes O(n) I think, instead of using .sort which is n*log(n)
def find_kth_largest(nums, k)
max_heap = MaxHeap.new()
nums.each {|val| max_heap.insert(val)}
i=1
while i<k
heap.delete_max()
i+=1
end
heap.delete_max()
end