zoukankan      html  css  js  c++  java
  • 747. Largest Number At Least Twice of Others

    In a given integer array nums, there is always exactly one largest element.

    Find whether the largest element in the array is at least twice as much as every other number in the array.

    If it is, return the index of the largest element, otherwise return -1.

    给一个数组,求最大值,如果最大值大于等于其他元素的两倍,那么就返回这个数的index,否则返回-1

    其实就是求最大值和次大值,看看最大值是不是大于等于次大值的两倍

    class Solution(object):
        def dominantIndex(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            index = -1
            first_max = 0
            second_max = 0
            for i in range(len(nums)):
                if nums[i] > first_max:
                    second_max = first_max
                    first_max = nums[i]
                    index = i
                elif nums[i] > second_max:
                    second_max = nums[i]
            if first_max >= second_max * 2:
                return index
            else:
                return -1
  • 相关阅读:
    安利博客
    python 的高阶算法之堆排序
    functools模块用途
    类型注解
    高阶函数和装饰器
    生成器

    递归函数
    匿名函数
    函数 的 返回值作用域
  • 原文地址:https://www.cnblogs.com/whatyouthink/p/13302012.html
Copyright © 2011-2022 走看看