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
  • 相关阅读:
    Solr4.8.0源码分析(12)之Lucene的索引文件(5)
    JAVA基础(1)之hashCode()
    Solr4.8.0源码分析(11)之Lucene的索引文件(4)
    检查数据不一致脚本
    索引的新理解
    数据库放到容器里
    动态规划
    每天晚上一个动态规划
    postgresql parallel join example
    名不正,则言不顺
  • 原文地址:https://www.cnblogs.com/bonelee/p/8729253.html
Copyright © 2011-2022 走看看