From 616ef8d8cfc0ac24372d8b712662da4fca3d5279 Mon Sep 17 00:00:00 2001 From: Jitendra Kumar Date: Tue, 21 Jan 2025 17:50:08 +0530 Subject: [PATCH] feat: add function to find majority element using hashmap problem: No.169 --- .../0169.Majority Element/Solution1.go | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 solution/0100-0199/0169.Majority Element/Solution1.go diff --git a/solution/0100-0199/0169.Majority Element/Solution1.go b/solution/0100-0199/0169.Majority Element/Solution1.go new file mode 100644 index 0000000000000..3f10fc777e3f3 --- /dev/null +++ b/solution/0100-0199/0169.Majority Element/Solution1.go @@ -0,0 +1,22 @@ +func findMajorityElement(nums []int) int { + // Create a hashmap to store the frequency of each element + frequency := make(map[int]int) + + // Traverse the array and count occurrences of each element + for _, num := range nums { + frequency[num]++ + } + + // Find the element with the maximum frequency + maxCount := 0 + var majorityElement int + for num, count := range frequency { + if count > maxCount { + maxCount = count + majorityElement = num + } + } + + // Return the element with the maximum frequency (not checking n/2 times explicitly) + return majorityElement +} \ No newline at end of file