Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 2465. Number of Distinct Averages

Rain Hu

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:

Example 1:

  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:

Constraints:


二、分析

三、解題

1. sort

int distinctAverages(vector<int>& nums) {
    sort(nums.begin(), nums.end());
    unordered_set<double> set;
    int n = nums.size();
    for (int i = 0; i < n/2; i++) {
        set.insert((nums[i] + nums[n-1-i])/2.0);
    }
    return set.size();
}

回目錄 Catalog


Share this post on:

Previous
[LeetCode] 2466. Count Ways To Build Good Strings
Next
[LeetCode] 223. Rectangle Area