Highest Rank Number in an Array in Golang

The challenge

Complete the method which returns the number which is most frequent in the given input array. If there is a tie for the most frequent number, return the largest number among them.

Note: no empty arrays will be given.

Examples

[12, 10, 8, 12, 7, 6, 4, 10, 12] --> 12 [12, 10, 8, 12, 7, 6, 4, 10, 12, 10] --> 12 [12, 10, 8, 8, 3, 3, 3, 3, 2, 4, 10, 12, 10] --> 3
Code language: CSS (css)

The solution in Golang

Option 1:

package solution func HighestRank(nums []int) int { mii, maxK, maxV := map[int]int{}, 0, 0 for _, v := range nums { mii[v]++ if mii[v] > maxV || (mii[v] == maxV && v > maxK) { maxK = v maxV = mii[v] } } return maxK }
Code language: Go (go)

Option 2:

package solution func HighestRank(nums []int) int { fs := make(map[int]int) for _, n := range nums { fs[n]++ } maxf, maxfn := 0, 0 for n, f := range fs { if f >= maxf && (f > maxf || n > maxfn) { maxf, maxfn = f, n } } return maxfn }
Code language: Go (go)

Option 3:

package solution func HighestRank(nums []int) int { occurrences := make(map[int]int) var max, val int for _, value := range nums { occurrences[value]++ } max, val = occurrences[nums[0]], nums[0] for value, times := range occurrences { if times > max { val = value max = times } else if times == max { if value > val { val = value } } } return val }
Code language: Go (go)

Test cases to validate our solution

package solution_test import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Tests", func() { Describe("Sample tests", func() { It("Sample test 1: 12, 10, 8, 12, 7, 6, 4, 10, 12", func() { Expect(HighestRank([]int{12, 10, 8, 12, 7, 6, 4, 10, 12 })).To(Equal(12)) }) }) })
Code language: Go (go)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments