When I was running the code for the leetcode question ""Moving Average from Data Stream"". I got a partly different output with the expected: Here is my code:
class MovingAverage {
int front = 0, rear = 0; Double sum = 0.00000;
int[] data;
public MovingAverage(int size) {
data = new int[size];
Arrays.fill(data, 0);
}
public double next(int val) {
if(data.length == 1){
data[rear] = val;
return val;
}else{
if(rear < data.length){
data[rear] = val;
sum = data[rear];
rear ;
return sum/rear;
}else{
sum -= data[front];
rear = (rear 1) % data.length - 1;
front = (front 1) % data.length ;
data[rear] = val;
sum = data[rear];
rear ;
return sum/data.length;
}
}
}
}
When I run the tast cases of the example provided, everything is ok. But when I run this edge case, thing is different: ["MovingAverage","next","next","next","next","next","next","next","next","next","next"] [[5],[12009],[1965],[-940],[-8516],[-16446],[7870],[25545],[-21028],[18430],[-23464]]
Anyone can help me pls? Is my code wrong or I didn't process the data conversion well?
CodePudding user response:
This logical check is incorrect:
if (rear < data.length)
In the corresponding else
block, when rear = data.length
, you set rear = (rear 1) % data.length - 1
, so rear < data.length
becomes true in the next iteration, and you go back to the if
block again. However, the logic to dequeue and update values is in the else
block (which is where you should end up once data
is filled completely). This is why you're getting an incorrect answer; if (rear < data.length)
isn't correct.
Replacing that condition with something like if (numberOfElementsTillNow < data.length)
should fix this issue.
CodePudding user response:
I revised my code, and the answer accepted:
class MovingAverage {
int front = 0, rear = 0; int sum = 0;
int[] data;
public MovingAverage(int size) {
data = new int[size];
Arrays.fill(data, 0);
}
public double next(int val) {
if(data.length == 1){
data[rear] = val;
return (double)val;
}else{
if(rear < data.length){
data[rear] = val;
sum = (int)data[rear];
rear ;
return sum * 1.0/rear;
}else{
sum -= (int)data[front % data.length];
data[rear % data.length] = val;
sum = (int)data[rear % data.length];
rear ;
front ;
return sum * 1.0/data.length;
}
}
}
}
This issue can be closed.