-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmajorityElement.go
More file actions
40 lines (36 loc) · 984 Bytes
/
Copy pathmajorityElement.go
File metadata and controls
40 lines (36 loc) · 984 Bytes
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
/* https://leetcode.com/problems/majority-element/#/description
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.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
*/
package larray
func majorityElement(nums []int) int {
/*maps := make(map[int]int)
mid := len(nums) / 2
for i := 0; i < len(nums); i++ {
if v, ok := maps[nums[i]]; ok {
v += 1
maps[nums[i]] = v
} else {
maps[nums[i]t ] = 1
}
if v, ok := maps[nums[i]]; ok && v > mid {
return nums[i]
}
}
panic("nums cannot be empty")
*/
cur, count := nums[0], 1
for i := 1; i < len(nums); i++ {
if count == 0 {
count = 1
cur = nums[i]
} else if cur == nums[i] {
count++
} else {
count--
}
}
return cur
}