PS/LeetCode

LeetCode / Array / 2090번 / K Radius Subarray Averages / JS

KimMinJun 2023. 6. 21. 19:24

< 문제 바로가기 >

 

K Radius Subarray Averages - LeetCode

Can you solve this real interview question? K Radius Subarray Averages - You are given a 0-indexed array nums of n integers, and an integer k. The k-radius average for a subarray of nums centered at some index i with the radius k is the average of all elem

leetcode.com

 

< 문제 간단설명 >

어떤 원이 k만큼의 반지름을 가질 때, 인덱스 하나마다 해당하는 요소를 중심으로 가질 때, 그 안에 들어오는 배열의 요소들의 평균을 구해서 반환하면 된다.

 

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number[]}
 */
var getAverages = function(nums, k) {
    let result = Array.from({ length: nums.length }, () => -1);

    if(nums.length < k) {
      return result;
    }

    for(let i=k; i<nums.length - k; i+=1) {
      let sum = 0;
      for(let j=i-k; j<=i+k; j+=1) {
        sum += nums[j];
      }
      // 반지름이 k이기 때문에 총 길이는 중심까지 합해서 k * 2 + 1
      result[i] = Math.floor(sum / (k * 2 + 1));
    }

    return result;
};