Open carloscn opened 11 months ago
static int32_t most_frequent_even(int32_t *nums, size_t nums_size)
{
int32_t ret = 0;
UTILS_CHECK_PTR(nums);
UTILS_CHECK_LEN(nums_size);
ret = utils_sort_int32_array(nums, nums_size, ORDER_BY_ASCEND);
UTILS_CHECK_RET(ret);
size_t count = 0, max_count = 0;
int32_t record = 0, min_record = INT32_MAX;
for (size_t i = 1; i < nums_size; i ++) {
count = (nums[i] != nums[i - 1])? 0 : count + 1;
if ((max_count < count) &&
(nums[i] & 0x1) == 0) {
max_count = count;
record = nums[i];
min_record = UTILS_MIN(record, min_record);
}
}
ret = (min_record == INT32_MAX) ? -1 : min_record;
finish:
return ret;
}
Description
Given an integer array nums, return the most frequent even element.
If there is a tie, return the smallest one. If there is no such element, return -1.
Example 1:
Input: nums = [0,1,2,2,4,4,1] Output: 2 Explanation: The even elements are 0, 2, and 4. Of these, 2 and 4 appear the most. We return the smallest one, which is 2.
Example 2:
Input: nums = [4,4,4,9,2,4] Output: 4 Explanation: 4 is the even element appears the most.
Example 3:
Input: nums = [29,47,21,41,13,37,25,7] Output: -1 Explanation: There is no even element.
Constraints:
1 <= nums.length <= 2000 0 <= nums[i] <= 105