[LeetCode] Number of Distinct Averages

2465. Number of Distinct Averages

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
int distinctAverages(vector<int>& nums) {
unordered_set<int> us;
sort(begin(nums),end(nums));
int l = 0, r = nums.size() - 1;
while(l < r) {
us.insert(nums[l] + nums[r]);
l += 1;
r -= 1;
}
return us.size();
}
};



Author: Song Hayoung
Link: https://songhayoung.github.io/2022/11/13/PS/LeetCode/number-of-distinct-averages/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.