-
Notifications
You must be signed in to change notification settings - Fork 43
/
largest-number-at-least-twice-of-others.py
72 lines (68 loc) · 1.66 KB
/
largest-number-at-least-twice-of-others.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
60
61
62
63
64
65
66
67
68
69
70
71
72
# V0
# V1
# https://blog.csdn.net/fuxuemingzhu/article/details/79188909
# IDEA : FIND THE 1ST, 2ND MAX
class Solution(object):
def dominantIndex(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 1:
return 0
largest = max(nums)
ind = nums.index(largest)
nums.pop(ind)
if largest >= 2 * max(nums):
return ind
else:
return -1
# V1'
# https://blog.csdn.net/fuxuemingzhu/article/details/79188909
# IDEA : SORT
class Solution(object):
def dominantIndex(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 1:
return 0
largest = max(nums)
ind = nums.index(largest)
nums.sort()
if largest >= 2 * nums[-2]:
return ind
else:
return -1
# V1''
# https://blog.csdn.net/fuxuemingzhu/article/details/79188909
# IDEA : HEAP
import heapq
class Solution(object):
def dominantIndex(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 1:
return 0
heap = [(-num, i) for i, num in enumerate(nums)]
heapq.heapify(heap)
largest, ind = heapq.heappop(heap)
if largest <= 2 * heapq.heappop(heap)[0]:
return ind
return -1
# V2
# Time: O(n)
# Space: O(1)
class Solution(object):
def dominantIndex(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
m = max(nums)
if all(m >= 2*x for x in nums if x != m):
return nums.index(m)
return -1