From 3390db92ab5cbc606c0a9efeda556426e7aba6dc Mon Sep 17 00:00:00 2001 From: ivan Date: Fri, 13 Dec 2024 04:25:53 -0600 Subject: [PATCH] adding majority element algo --- .../majority_element.py | 22 +++++++++++++++++++ .../test_majority_element_round_12.py | 18 +++++++++++++++ 2 files changed, 40 insertions(+) create mode 100644 src/my_project/interviews/top_150_questions_round_12/majority_element.py create mode 100644 tests/test_150_questions_round_12/test_majority_element_round_12.py diff --git a/src/my_project/interviews/top_150_questions_round_12/majority_element.py b/src/my_project/interviews/top_150_questions_round_12/majority_element.py new file mode 100644 index 00000000..65d44398 --- /dev/null +++ b/src/my_project/interviews/top_150_questions_round_12/majority_element.py @@ -0,0 +1,22 @@ +from typing import List, Union, Collection, Mapping, Optional +from abc import ABC, abstractmethod + +class Solution: + def majorityElement(self, nums: List[int]) -> int: + + dic_answer = dict() + len_nums = len(nums) + + for i in range(len_nums): + + if nums[i] not in dic_answer: + dic_answer[nums[i]] = 1 + else: + dic_answer[nums[i]] += 1 + + if dic_answer[nums[i]] > len_nums//2: + return nums[i] + else: + pass + + return -1 \ No newline at end of file diff --git a/tests/test_150_questions_round_12/test_majority_element_round_12.py b/tests/test_150_questions_round_12/test_majority_element_round_12.py new file mode 100644 index 00000000..70e34c75 --- /dev/null +++ b/tests/test_150_questions_round_12/test_majority_element_round_12.py @@ -0,0 +1,18 @@ +import unittest +from src.my_project.interviews.top_150_questions_round_12\ +.majority_element import Solution + + +class MajorityElementTestCase(unittest.TestCase): + + def test_is_major_element(self): + solution = Solution() + output = solution.majorityElement(nums=[3,2,3]) + target = 3 + self.assertEqual(output, target) + + def test_is_no_major_element(self): + solution = Solution() + output = solution.majorityElement(nums = [1,2,3]) + target = -1 + self.assertEqual(output, target) \ No newline at end of file