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
  • 相关阅读:
    crash reporting system for Windows applications
    1
    qt 试用 (3)配置编译源代码及调试
    kd tree & ray tracing
    new
    KMP算法中关于next数组的探究
    teamviewer vs echovnc
    NAT之stun确定nat类型
    Wireshark
    GNU httptunnel,当SSH被block时的选择
  • 原文地址:https://www.cnblogs.com/bonelee/p/8729253.html
Copyright © 2011-2022 走看看