I am trying to find the highest frequency element in the given as follows.
First, I am trying to build a dictionary and count the each element based on frequency.
I am stuck how to extract max value from the constructed dictionary.
Input: [3,2,3]
Output: 3
func majorityElement(_ nums1: [Int]) -> Int {
var num1Dict = Dictionary(nums1.map{ ($0, 1) }, uniquingKeysWith : +)
return num1Dict.values.max() // ????
}
You have correctly constructed num1Dict, which will be something like this for the input [3,2,3]:
[2:1, 3:2]
values.max() will return 2, because out of all the values in the dictionary (1 and 2), 2 is the highest.
See your error now?
You need to return the key associated with the highest value, not the highest value.
One very straightforward way is to do this:
func majorityElement(_ nums1: [Int]) -> Int? { // you should probably return an optional here in case nums1 is empty
let num1Dict = Dictionary(nums1.map{ ($0, 1) }, uniquingKeysWith : +)
var currentHigh = Int.min
var mostOccurence: Int?
for kvp in num1Dict {
if kvp.value > currentHigh {
mostOccurence = kvp.key
currentHigh = kvp.value
}
}
return mostOccurence
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With