[LeetCode] Number of Distinct Averages

준규·2023년 2월 25일
0

1.문제


You are given a 0-indexed integer array nums of even length.

As long as nums is not empty, you must repetitively:

  • Find the minimum number in nums and remove it.
  • Find the maximum number in nums and remove it.
  • Calculate the average of the two removed numbers.

The average of two numbers a and b is (a + b) / 2.

  • For example, the average of 2 and 3 is (2 + 3) / 2 = 2.5.

Return the number of distinct averages calculated using the above process.

Note that when there is a tie for a minimum or maximum number, any can be removed.


길이가 짝수인 숫자배열 nums가 주어질 때 최대한 배열의 max , min 값을 삭제하고 삭제한 두 값의 평균을 구하는 과정을 거친다. 최대한 과정을 거친 후 나온 평균의 갯수를 리턴하면 된다(중복 x)


Example 1

Input: nums = [4,1,4,0,3,5]
Output: 2
Explanation:
1. Remove 0 and 5, and the average is (0 + 5) / 2 = 2.5. Now, nums = [4,1,4,3].
2. Remove 1 and 4. The average is (1 + 4) / 2 = 2.5, and nums = [4,3].
3. Remove 3 and 4, and the average is (3 + 4) / 2 = 3.5.
Since there are 2 distinct numbers among 2.5, 2.5, and 3.5, we return 2.

Example 2

Input: nums = [1,100]
Output: 1
Explanation:
There is only one average to be calculated after removing 1 and 100, so we return 1.

Constraints:

  • 2 <= nums.length <= 100
  • nums.length is even.
  • 0 <= nums[i] <= 100

2.풀이

  1. 배열이 빈배열이 될 때 까지 반복문을 수행한다.
  2. 최댓값과 최솟값을 배열에서 삭제하고 두 수의 평균을 구해서 배열에 저장한다.
  3. 평균 배열을 중복값을 없앤 뒤 길이를 리턴한다.

/**
 * @param {number[]} nums
 * @return {number}
 */
const distinctAverages = function (nums) {
  const average = [];
  while (nums.length > 0) {
    // 배열 내 최댓값을 구하고 배열에서 삭제
    const max = Math.max(...nums);
    const maxIndex = nums.indexOf(max);
    nums.splice(maxIndex, 1);

    // 배열 내 최솟값을 구하고 배열에서 삭제
    const min = Math.min(...nums);
    const minIndex = nums.indexOf(min);
    nums.splice(minIndex, 1);

    // 최댓값과 최솟값의 평균 구하기
    average.push((max + min) / 2);
  }

  // 중복되지 않는 평균의 갯수 리턴
  return [...new Set(average)].length;
};

3.결과

profile
안녕하세요 :)

0개의 댓글