Input: nums =[4,1,4,0,3,5]Output: 2Explanation:
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 return2.
Sort the array. In each step, remove the smallest and largest elements, compute their average, and store it in a set. The number of distinct averages is the size of the set.
#include<vector>#include<set>#include<algorithm>usingnamespace std;
classSolution {
public:int distinctAverages(vector<int>& nums) {
sort(nums.begin(), nums.end());
set<double> s;
int l =0, r = nums.size()-1;
while (l < r) {
s.insert((nums[l]+nums[r])/2.0);
++l; --r;
}
return s.size();
}
};
1
2
3
4
5
6
7
8
9
10
11
funcdistinctAverages(nums []int) int {
sort.Ints(nums)
s:=map[float64]struct{}{}
l, r:=0, len(nums)-1forl < r {
avg:= float64(nums[l]+nums[r])/2.0s[avg]=struct{}{}
l++; r-- }
return len(s)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
import java.util.*;
classSolution {
publicintdistinctAverages(int[] nums) {
Arrays.sort(nums);
Set<Double> set =new HashSet<>();
int l = 0, r = nums.length-1;
while (l < r) {
set.add((nums[l]+nums[r])/2.0);
l++; r--;
}
return set.size();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
fundistinctAverages(nums: IntArray): Int {
nums.sort()
val set = mutableSetOf<Double>()
var l = 0; var r = nums.size-1while (l < r) {
set.add((nums[l]+nums[r])/2.0)
l++; r-- }
returnset.size
}
}
1
2
3
4
5
6
7
8
9
classSolution:
defdistinctAverages(self, nums: List[int]) -> int:
nums.sort()
s = set()
l, r =0, len(nums)-1while l < r:
s.add((nums[l]+nums[r])/2)
l +=1; r -=1return len(s)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
use std::collections::HashSet;
impl Solution {
pubfndistinct_averages(nums: Vec<i32>) -> i32 {
letmut nums = nums;
nums.sort();
letmut s = HashSet::new();
let (mut l, mut r) = (0, nums.len()-1);
while l < r {
s.insert((nums[l]+nums[r]) asf64/2.0);
l +=1; r -=1;
}
s.len() asi32 }
}