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.

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

这题还挺简单的,就是求一个数组里最大和最小数的平均值,每次求完把最大和最小remove,再对剩下的进行同样的操作,问最后有多少个distinct的平均值。

就,好像不得不sort,以及求distinct平均值的话,不得不用一下set,所以这就是主要的时间和空间复杂度消耗之处了,无法优化了。写的时候注意求平均值的时候得1.0 * (a + b) / 2,不然最后出来的就算是double也是.0结尾的。

class Solution {
    public int distinctAverages(int[] nums) {
        Arrays.sort(nums);
        int i = 0;
        int j = nums.length - 1;
        Set<Double> set = new HashSet<>();
        while (i <= j) {
            double avg = 1.0 * (nums[i] + nums[j]) / 2;
            if (!set.contains(avg)) {
                set.add(avg);
            }
            i++;
            j--;
        }
        return set.size();
    }
}

猜你喜欢

转载自blog.csdn.net/qq_37333947/article/details/132808453