forked from algorithm001/algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode_703_3.c
More file actions
88 lines (68 loc) · 1.63 KB
/
Copy pathLeetCode_703_3.c
File metadata and controls
88 lines (68 loc) · 1.63 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
typedef struct {
int* arr;
int length;
int size;
} KthLargest;
int kthLargestAdd(KthLargest* obj, int val);
void KthLargestInsert(KthLargest* obj, int val){
int loop;
//isFull, error
//arr[0] is not used
obj->size += 1;
for(loop = obj->size; loop > 1 && val < obj->arr[loop/2]; loop/=2){
obj->arr[loop] = obj->arr[loop/2];
}
obj->arr[loop] = val;
return;
}
KthLargest* kthLargestCreate(int k, int* nums, int numsSize) {
KthLargest* obj = malloc(sizeof(KthLargest));
obj->arr = calloc((k + 1), sizeof(int));
obj->length = k;
obj->size = 0;
int loop;
for(loop = 0; loop < numsSize; loop++){
kthLargestAdd(obj, nums[loop]);
}
return obj;
}
int kthLargestAdd(KthLargest* obj, int val) {
#if 1
int loop;
int *arr = obj->arr;
int size = obj->size;
int child;
if(obj->length != size){
KthLargestInsert(obj, val);
return arr[1];
}
if(val <= obj->arr[1]){
return obj->arr[1];
}
for(loop = 1; 2*loop <= size; loop = child){
child = 2*loop;
if(child != size && arr[child+1] < arr[child]){
child += 1;
}
if(val > arr[child]){
arr[loop] = arr[child];
}
else{
break;
}
}
arr[loop] = val;
#endif
return obj->arr[1];
}
void kthLargestFree(KthLargest* obj) {
free(obj->arr);
free(obj);
return;
}
/**
* Your KthLargest struct will be instantiated and called as such:
* KthLargest* obj = kthLargestCreate(k, nums, numsSize);
* int param_1 = kthLargestAdd(obj, val);
* kthLargestFree(obj);
*/