zoukankan      html  css  js  c++  java
  • leetcode 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.

    Example 1:

    Input: nums = [3, 6, 1, 0]
    Output: 1
    Explanation: 6 is the largest integer, and for every other number in the array x,
    6 is more than twice as big as x.  The index of value 6 is 1, so we return 1.
    

    Example 2:

    Input: nums = [1, 2, 3, 4]
    Output: -1
    Explanation: 4 isn't at least as big as twice the value of 3, so we return -1.
    

    Note:

    1. nums will have a length in the range [1, 50].
    2. Every nums[i] will be an integer in the range [0, 99].

    最直观解法:

    class Solution(object):
        def dominantIndex(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            max_n = max(nums)
            max_cnt = 0
            ans = -1
            for i,n in enumerate(nums):
                if n != max_n:
                    if max_n < n*2:
                        return -1
                else:
                    max_cnt += 1
                    if max_cnt > 1:
                        return -1
                    ans = i
            return ans

    数学解法:

    class Solution(object):
        def dominantIndex(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            max1, max2 = float('-inf'), float('-inf')
            ans = -1
            for i, n in enumerate(nums):
                if n > max1:
                    max1, max2 = n, max1
                    ans = i
                elif n > max2:
                    max2 = n
            return -1 if max2*2 > max1 else ans
  • 相关阅读:
    redis 集群
    redis--主从复制
    redis--AOF
    React——组件
    React——文件夹分析
    WEB面试
    WEB基础——接收后台文件方法
    WEB基础——AJAX
    C#进阶——IOC
    C#基础——HttpContext
  • 原文地址:https://www.cnblogs.com/bonelee/p/8729253.html
Copyright © 2011-2022 走看看