题目描述
在一个给定的数组nums中,总是存在一个最大元素 。
查找数组中的最大元素是否至少是数组中每个其他数字的两倍。
如果是,则返回最大元素的索引,否则返回-1。
提示:
- nums 的长度范围在[1, 50].
- 每个 nums[i] 的整数范围在 [0, 100].
题目地址:https://leetcode-cn.com/problems/largest-number-at-least-twice-of-others/
方法一:
初步实现
class Solution:
def dominantIndex(self, nums: List[int]) -> int:
m = max(nums)
anums = nums
for i in anums:
if i == m:
continue
if 2*i <= m:
continue
else:
return -1
return nums.index(m)
- 遍历数组时没有将最大值本身排除在外
- 拷贝数组需要额外空间
改进:
- 找到最大值后直接记录其索引
- 在遍历时直接加入条件判断,充分利用python语言优势。
class Solution:
def dominantIndex(self, nums: List[int]) -> int:
m = max(nums)
m_index = nums.index(m)
if all(2*n <= m for n in nums if n != m):
return m_index
return -1
方法二:
排序,比较最大值与第二大值两倍的关系即可。
遍历数组找前二大值:
class Solution:
def dominantIndex(self, nums: List[int]) -> int:
nmax = 0
nmax_index = 0
smax = 0
for x in nums:
if x > nmax:
smax = nmax
nmax = x
nmax_index = nums.index(x)
elif x > smax:
smax = x
return nmax_index if nmax >= 2*smax else -1
直接用sorted()
class Solution:
def dominantIndex(self, nums: List[int]) -> int:
# 只有一个元素的情况
if len(nums)==1: return 0
l = sorted(nums, reverse=True)
return nums.index(l[0]) if l[0]>=2*l[1] else -1