2455. Average Value of Even Numbers That Are Divisible by Three
Description
Given an integer array nums of positive integers, return the average value of all even integers that are divisible by 3.
Note that the average of n elements is the sum of the n elements divided by n and rounded down to the nearest integer.
Example 1:
Input: nums = [1,3,6,10,12,15] Output: 9 Explanation: 6 and 12 are even numbers that are divisible by 3. (6 + 12) / 2 = 9.
Example 2:
Input: nums = [1,2,4,7,10] Output: 0 Explanation: There is no single number that satisfies the requirement, so return 0.
Constraints:
1 <= nums.length <= 10001 <= nums[i] <= 1000
Solutions
Solution 1: Simulation
Thinking
At \(n\le 1000\), even and divisible by three means divisible by \(6\). Sum those values and count them; return \(0\) if the count is zero, else integer-divide.
We notice that an even number divisible by \(3\) must be a multiple of \(6\). Therefore, we only need to traverse the array, count the sum and the number of all multiples of \(6\), and then calculate the average.
The time complexity is \(O(n)\), where \(n\) is the length of the array. The space complexity is \(O(1)\).
1 2 3 4 5 6 7 8 | |
1 2 3 4 5 6 7 8 9 10 11 12 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
1 2 3 4 5 6 7 8 9 10 | |
Solution 2
Thinking
Method 1 already accumulates \(x\bmod 6=0\). Filtering into a list and dividing the sum by its length is the same average, with an extra allocation.
1 2 3 4 5 6 7 8 9 10 11 | |