leetcode#747. 至少是其他数字两倍的最大数

题目描述

在一个给定的数组nums中,总是存在一个最大元素
查找数组中的最大元素是否至少是数组中每个其他数字的两倍
如果是,则返回最大元素的索引,否则返回-1。

提示:

  1. nums 的长度范围在[1, 50].
  2. 每个 nums[i] 的整数范围在 [0, 100].

题目地址:https://leetcode-cn.com/problems/largest-number-at-least-twice-of-others/

方法一:

参考文档

Created with Raphaël 2.2.0 输入数组nums 找出最大元素max 该元素 > 其他每个元素两倍? 返回index 返回-1 yes no

初步实现

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值