We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent eb91bc9 commit 14bbc3eCopy full SHA for 14bbc3e
arrays/169_Majority_Element.py
@@ -0,0 +1,29 @@
1
+def majority_element(nums: list[int]) -> int:
2
+ """Finds the majority element in a list of integers.
3
+
4
+ The majority element is the element that appears more than ⌊n / 2⌋ times,
5
+ where n is the size of the array. It is assumed that the majority element always exists.
6
7
+ :param nums: A list of integers where the majority element is to be found.
8
+ :return: The majority element in the list.
9
+ """
10
11
+ counter = 1
12
+ current_majority_element = nums[0]
13
14
+ for num in nums[1:]:
15
+ if current_majority_element != num:
16
+ if counter:
17
+ counter -= 1
18
+ if counter == 0:
19
+ current_majority_element = num
20
21
+ else:
22
+ counter += 1
23
24
+ return current_majority_element
25
26
27
+assert majority_element(nums=[3,2,3]) == 3, 'Test 1 failed'
28
+assert majority_element(nums=[2,2,1,1,1,2,2]) == 2, 'Test 2 failed'
29
+assert majority_element(nums=[6,5,5]) == 5, 'Test 3 failed'
AltStyle によって変換されたページ (->オリジナル) / アドレス: モード: デフォルト 音声ブラウザ ルビ付き 配色反転 文字拡大 モバイル
0 commit comments