classSolution: defmostFrequentEven(self, nums: List[int]) -> int: count = Counter() for x in nums: if x % 2 == 0: count[x] += 1 res, ct = -1, 0 for k, v in count.items(): if res == -1or v > ct or (v == ct and res > k): res = k ct = v return res
[sol1-C#]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
publicclassSolution { publicintMostFrequentEven(int[] nums) { IDictionary<int, int> count = new Dictionary<int, int>(); foreach (int x in nums) { if (x % 2 == 0) { count.TryAdd(x, 0); count[x]++; } } int res = -1, ct = 0; foreach (KeyValuePair<int, int> pair in count) { if (res == -1 || pair.Value > ct || pair.Value == ct && res > pair.Key) { res = pair.Key; ct = pair.Value; } } return res; } }
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
funcmostFrequentEven(nums []int)int { count := map[int]int{} for _, x := range nums { if x % 2 == 0 { count[x]++ } } res, ct := -1, 0 for k, v := range count { if res == -1 || ct < v || ct == v && k < res { res = k ct = v } } return res }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
var mostFrequentEven = function(nums) { let count = newMap(); for (let x of nums) { if (x % 2 == 0) { count.set(x, (count.get(x) || 0) + 1); } } let res = -1, ct = 0; for (let [k, v] of count) { if (res == -1 || v > ct || v == ct && k < res) { res = k; ct = v; } } return res; };