File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change
1
+ ##==================================
2
+ ## Leetcode
3
+ ## Student: Vandit Jyotindra Gajjar
4
+ ## Year: 2020
5
+ ## Problem: 169
6
+ ## Problem Name: Majority Element
7
+ ##===================================
8
+ #
9
+ #Given an array of size n, find the majority element.
10
+ #The majority element is the element that appears more than n/2 times.
11
+ #
12
+ #You may assume that the array is non-empty and the majority element always exist in the array.
13
+ #
14
+ #Example 1:
15
+ #
16
+ #Input: [3,2,3]
17
+ #Output: 3
18
+ #Example 2:
19
+ #
20
+ #Input: [2,2,1,1,1,2,2]
21
+ #Output: 2
22
+ from collections import Counter as c #Import Counter module
23
+ class Solution :
24
+ def majorityElement (self , nums ):
25
+ tmp = c (nums ) #Initialize tmp which counts the number of elements and store in dictionary number : occurrence manner
26
+ for key , val in tmp .items (): #Loop through tmp
27
+ if val > (len (nums ) / 2 ): #Condition-check: If value is greater than length of array / 2
28
+ return key #We return key for that value
29
+ #Example:
30
+ #nums = [3, 2, 3]
31
+ #tmp = Counter({3:2, 2:1})
32
+ #key, val = (3, 2)
33
+ #key, val = (2, 1)
34
+ #Condition-check: 2 > (3 / 2): return key Here value is 2, and for that value key is 3, so we'll return 3 which is majority element
You can’t perform that action at this time.
0 commit comments