-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMajority_Element.py
More file actions
95 lines (69 loc) · 2.11 KB
/
Copy pathMajority_Element.py
File metadata and controls
95 lines (69 loc) · 2.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# -*- coding: utf-8 -*-
"""
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
"""
from collections import defaultdict
class Solution:
# @param num, a list of integers
# @return an integer
def majorityElement(self, nums): # using moore voting alg.
major = nums[0]
vote = 1
for i in range(1, len(nums)):
# no major so nums[i] become a major
if vote == 0:
major = nums[i]
vote += 1
# nums[i] is still a major, inc. its vote
elif major == nums[i]:
vote += 1
# nums[i] is new candidate but with less vote
# than major, dec. major vote
else:
vote -= 1
return major
# @param num, a list of integers
# @return an integer
def majorityElementBit(self, nums): # using bit manipulation
int_size = 32
majority_element = 0
# loop over each bit
for i in range(int_size):
zero_count = 0
one_count = 0
# check i(th) bit for all
for num in nums:
if abs(num) & (1 << i) != 0: # i(th) bit is one
one_count += 1
else:
zero_count += 1
# majority element i(th) bit is the bit with the larger count
if one_count > zero_count:
majority_element = majority_element | (1 << i)
else:
majority_element = majority_element & ~(1 << i)
# check if majority element is negative or positive
# this is not needed in java
negative_count = 0
for num in nums:
if num < 0:
negative_count += 1
# major element is negative number
if negative_count > len(nums) / 2:
majority_element = -1 * majority_element
return majority_element
# @param num, a list of integers
# @return an integer
def majorityElementHash(self, nums): # use hash
n = len(nums)
if n == 1: # base case
return nums[0]
target = int(len(nums)/2.0)
count = defaultdict(int) # key = number, value = number of appearance
for num in nums:
count[num] += 1
if count[num] > target:
return num
s = Solution()
print s.majorityElement([6,5,5])