-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathKRadiusSubarray.java
More file actions
55 lines (42 loc) · 1.14 KB
/
Copy pathKRadiusSubarray.java
File metadata and controls
55 lines (42 loc) · 1.14 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
/**
* Things to remember
* 1. array initialization with default values
*
*/
import java.util.Arrays;
class Solution {
public int[] getAverages(int[] nums, int k) {
int n = nums.length;
int[] output = new int[n];
Arrays.fill(output, -1);
if (k > n){
return output;
}
double sumLeft = 0;
for (int i = 0; i < k; i++) {
sumLeft += nums[i];
}
double sumRight = 0;
for (int i = k + 1 ; i <= 2 * k ; i++){
if (i < n) {
sumRight += nums[i];
}
}
int totalElement = 2 * k + 1;
for (int i = k; i < n - k; i++) {
double sum = (sumLeft + sumRight + nums[i]) / totalElement;
output[i] = (int) sum;
sumLeft = sumLeft + nums[i];
if (i - k >= 0 ){
sumLeft -= nums[i - k] ;
}
if (i + 1 < n ) {
sumRight = sumRight - nums[i + 1];
}
if (i + k + 1 < n){
sumRight = sumRight + nums[ i + k + 1];
}
}
return output;
}
}