Untitled
import java.util.Arrays; class Solution { public int[] getAverages(int[] nums, int k) { int n = nums.length; if (k == 0) { return nums; // If k is 0, the result is the same as the input } int[] result = new int[n]; Arrays.fill(result, -1); // Initialize the result array with -1 // If the window size is larger than the array, return result as it is if (n < 2 * k + 1) { return result; } long windowSum = 0; int i = 0; // Left pointer int j = 0; // Right pointer // Compute the sum of the first window while (j <= 2 * k) { windowSum += nums[j]; j++; } // Calculate the first average result[k] = (int) (windowSum / (2 * k + 1)); // Slide the window across the array while (j < n) { windowSum = windowSum - nums[i] + nums[j]; // Adjust window sum i++; // Move left pointer result[i + k] = (int) (windowSum / (2 * k + 1)); // Calculate the average j++; // Move right pointer } return result; } }
Leave a Comment