-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path1287.element-appearing-more-than-25-in-sorted-array.py
59 lines (39 loc) · 1.37 KB
/
1287.element-appearing-more-than-25-in-sorted-array.py
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
from lc import *
# boyer-moore https://leetcode.com/problems/element-appearing-more-than-25-in-sorted-array/discuss/521862/JavaScript-Boyer-Moore-Voting-Algorithm
class Solution:
def findSpecialInteger(self, a: List[int]) -> int:
r = c = 0
for x in a:
if c==0 or c==1:
r = x
c += 3 if r==x else -1
return r
# editorial (log n)
class Solution:
def findSpecialInteger(self, a: List[int]) -> int:
n=len(a);return next(x for x in(a[n//4],a[n//2],a[3*n//4])if bisect_right(a,x)-bisect_left(a,x)>n/4)
class Solution:
def findSpecialInteger(self, a: List[int]) -> int:
n=len(a);return next(u for i in(1,2,3)if a[t:=bisect_left(a,u:=a[i*n//4])]==a[t+n//4])
# https://leetcode.com/problems/element-appearing-more-than-25-in-sorted-array/discuss/930267/One-line-solution
class Solution:
def findSpecialInteger(self, a: List[int]) -> int:
return Counter(a).most_common()[0][0]
test('''
1287. Element Appearing More Than 25% In Sorted Array
Easy
1048
52
Add to List
Share
Given an integer array sorted in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time, return that integer.
Example 1:
Input: arr = [1,2,2,6,6,6,6,7,10]
Output: 6
Example 2:
Input: arr = [1,1]
Output: 1
Constraints:
1 <= arr.length <= 10^4
0 <= arr[i] <= 10^5
''')