-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode-264.c
More file actions
88 lines (77 loc) · 1.82 KB
/
LeetCode-264.c
File metadata and controls
88 lines (77 loc) · 1.82 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
/*************************************************************************
w > File Name: LeetCode-264.c
> Author: ltw
> Mail: [email protected]
> Created Time: Thu 21 May 2020 10:50:44 PM CST
************************************************************************/
#define swap(a, b) { \
__typeof(a) __temp = a; \
a = b, b = __temp; \
}
typedef struct Heap {
long long *data;
int n, size;
} Heap;
Heap *init(int n) {
Heap *h = (Heap *)malloc(sizeof(Heap));
h->n = 0;
h->size = n + 1;
h->data = (long long *)malloc(sizeof(long long) * h->size);
return h;
}
int empty(Heap *h) {
return h->n == 0;
}
#define V(x) h->data[x]
void push(Heap *h, long long val) {
h->data[++(h->n)] = val;
int ind = h->n;
while (ind > 1 && V(ind) < V(ind >> 1)) {
swap(V(ind), V(ind >> 1));
ind >>= 1;
}
return ;
}
long long top(Heap *h) { return V(1); }
void pop(Heap *h) {
if (empty(h)) return ;
V(1) = V(h->n);
(h->n)--;
int ind = 1;
while ((ind << 1) <= h->n) {
int temp = ind, l = ind << 1, r = ind << 1 | 1;
if (V(l) < V(temp)) temp = l;
if (r <= h->n && V(r) < V(temp)) temp = r;
if (temp == ind) break;
swap(V(ind), V(temp));
ind = temp;
}
return ;
}
void clear(Heap *h) {
if (h == NULL) return ;
free(h->data);
free(h);
return ;
}
int nthUglyNumber(int n){
Heap *h = init(3 * n);
push(h, 1);
long long ans = 0;
while (n--) {
ans = top(h);
pop(h);
if (ans % 5 == 0) {
push(h, 5 * ans);
} else if (ans % 3 == 0) {
push(h, 3 * ans);
push(h, 5 * ans);
} else {
push(h, 2 * ans);
push(h, 3 * ans);
push(h, 5 * ans);
}
}
clear(h);
return ans;
}