Leetcode 2465. Number of Distinct Averages
You are given an array of nums
consisting of integers. You need to compute the number of distinct averages that can be obtained by repeatedly picking and removing the highest and lowest elements from the array until no elements are left. The average is defined as the sum of the picked elements divided by 2.
0
.To solve this problem, we can use the following strategy:
#include <iostream>
#include <vector>
#include <set>
#include <algorithm>
int distinctAverages(std::vector<int>& nums) {
// Sort the nums array
std::sort(nums.begin(), nums.end());
// Hash set to store distinct averages
std::set<double> distinctAvg;
// Two pointer technique
int left = 0;
int right = nums.size() - 1;
while (left < right) {
double avg = (nums[left] + nums[right]) / 2.0;
distinctAvg.insert(avg);
left++;
right--;
}
// Return the number of distinct averages
return distinctAvg.size();
}
int main() {
std::vector<int> nums = {4, 1, 4, 0, 3, 5}; // Example input
std::cout << "Number of distinct averages: " << distinctAverages(nums) << std::endl;
return 0;
}
Therefore, the overall time complexity is (O(n \log n)).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?