carloscn / structstudy

Leetcode daily trainning by using C/C++/RUST programming.
4 stars 1 forks source link

leetcode2455: Average Value of Even Numbers That Are Divisible by Three #401

Open carloscn opened 11 months ago

carloscn commented 11 months ago

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 <= 1000 1 <= nums[i] <= 1000

carloscn commented 11 months ago

Analysis

static int32_t average_value(int32_t *nums, size_t nums_size)
{
    int32_t ret = 0;

    UTILS_CHECK_PTR(nums);
    UTILS_CHECK_LEN(nums_size);

    int32_t count = 0;
    for (size_t i = 0; i < nums_size; i ++) {
        if ((nums[i] % 3) == 0) {
            ret += nums[i];
            count ++;
        }
    }

    if (count != 0) {
        ret /= count;
    }

finish:
    return ret;
}
carloscn commented 11 months ago

Code

https://review.gerrithub.io/c/carloscn/structstudy/+/1171192 https://github.com/carloscn/structstudy/commit/37af336e859faeff3f35f063a631fa447fecf456