forked from super30admin/Competitive-Coding-1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem2.java
More file actions
109 lines (87 loc) · 2.42 KB
/
Problem2.java
File metadata and controls
109 lines (87 loc) · 2.42 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
//Design Min Heap
class MyMinHeap {
private int[] heap;
private int size;
private int maxSize;
public MyMinHeap(int capacity) {
this.maxSize = capacity;
this.size = 0;
heap = new int[capacity];
}
private int parent(int i) {
return (i - 1) / 2;
}
private int leftChild(int i) {
return 2 * i + 1;
}
private int rightChild(int i) {
return 2 * i + 2;
}
private boolean isLeaf(int i) {
return i >= size / 2 && i < size;
}
private void swap(int i, int j) {
int temp = heap[i];
heap[i] = heap[j];
heap[j] = temp;
}
private void heapify(int i) {
if (isLeaf(i)) return;
int left = leftChild(i);
int right = rightChild(i);
int smallest = i;
if (left < size && heap[left] < heap[smallest]) {
smallest = left;
}
if (right < size && heap[right] < heap[smallest]) {
smallest = right;
}
if (smallest != i) {
swap(i, smallest);
heapify(smallest);
}
}
public void insert(int val) {
if (size >= maxSize) return;
heap[size] = val;
int current = size;
size++;
while (current > 0 && heap[current] < heap[parent(current)]) {
swap(current, parent(current));
current = parent(current);
}
}
public int removeMin() {
if (size == 0) return -1;
int min = heap[0];
heap[0] = heap[size - 1];
size--;
heapify(0);
return min;
}
public void printHeap() {
for (int i = 0; i <= (size - 2) / 2; i++) {
System.out.print("PARENT: " + heap[i]);
if (leftChild(i) < size)
System.out.print(" LEFT: " + heap[leftChild(i)]);
if (rightChild(i) < size)
System.out.print(" RIGHT: " + heap[rightChild(i)]);
System.out.println();
}
}
public static void main(String[] args) {
MyMinHeap heap = new MyMinHeap(15);
heap.insert(5);
heap.insert(3);
heap.insert(17);
heap.insert(10);
heap.insert(84);
heap.insert(19);
heap.insert(6);
heap.insert(22);
heap.insert(9);
System.out.println("Min Heap:");
heap.printHeap();
System.out.println("Removed Min: " + heap.removeMin());
}
}