-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy path346. Moving Average from Data Stream.c
73 lines (65 loc) · 1.49 KB
/
346. Moving Average from Data Stream.c
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
/*
346. Moving Average from Data Stream
Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.
For example,
MovingAverage m = new MovingAverage(3);
m.next(1) = 1
m.next(10) = (1 + 10) / 2
m.next(3) = (1 + 10 + 3) / 3
m.next(5) = (10 + 3 + 5) / 3
*/
typedef struct {
int *data;
int sum;
int n;
int size;
} MovingAverage;
/** Initialize your data structure here. */
MovingAverage* movingAverageCreate(int size) {
int *p;
MovingAverage *m;
m = calloc(1, sizeof(*m));
p = calloc(size, sizeof(*p));
//assert(m && p);
m->data = p;
m->sum = 0;
m->n = 0;
m->size = size;
return m;
}
double movingAverageNext(MovingAverage* obj, int val) {
int *slot, old;
slot = &obj->data[obj->n % obj->size];
old = *slot;
*slot = val;
obj->n ++;
obj->sum = obj->sum - old + val;
if (obj->n < obj->size) return (double)obj->sum / (double)obj->n;
return (double)obj->sum / (double)obj->size;
}
void movingAverageFree(MovingAverage* obj) {
free(obj->data);
free(obj);
}
/**
* Your MovingAverage struct will be instantiated and called as such:
* struct MovingAverage* obj = movingAverageCreate(size);
* double param_1 = movingAverageNext(obj, val);
* movingAverageFree(obj);
*/
/*
Difficulty:Easy
Total Accepted:25.3K
Total Submissions:43K
Companies Google
Related Topics Design Queue
*/