Skip to content

Commit 3078844

Browse files
committed
Check If a Number Is Majority Element in a Sorted Array
1 parent ad48a5d commit 3078844

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# Given an array nums sorted in non-decreasing order, and a number target,
2+
# return True if and only if target is a majority element.
3+
#
4+
# A majority element is an element that appears more than N/2 times in an array of length N.
5+
#
6+
# Example 1:
7+
#
8+
# Input: nums = [2,4,5,5,5,5,5,6,6], target = 5
9+
# Output: true
10+
# Explanation:
11+
# The value 5 appears 5 times and the length of the array is 9.
12+
# Thus, 5 is a majority element because 5 > 9/2 is true.
13+
# Example 2:
14+
#
15+
# Input: nums = [10,100,101,101], target = 101
16+
# Output: false
17+
# Explanation:
18+
# The value 101 appears 2 times and the length of the array is 4.
19+
# Thus, 101 is not a majority element because 2 > 4/2 is false.
20+
21+
import collections
22+
23+
24+
class Solution:
25+
def isMajorityElement(self, nums, target):
26+
dict = collections.Counter(nums)
27+
if len(nums) == 1:
28+
return nums[0] == target
29+
30+
k = nums[len(nums) // 2]
31+
if dict[k] > len(nums) // 2:
32+
return True
33+
34+
return False

0 commit comments

Comments
 (0)