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
  • 相关阅读:
    2021/9/20 开始排序算法
    快速排序(自己版本)
    2021/9/17(栈实现+中后缀表达式求值)
    2021/9/18+19(中缀转后缀 + 递归 迷宫 + 八皇后)
    20212021/9/13 稀疏数组
    2021/9/12 线性表之ArrayList
    开发环境重整
    Nginx入门
    《财富的帝国》读书笔记
    Linux入门
  • 原文地址:https://www.cnblogs.com/bonelee/p/8729253.html
Copyright © 2011-2022 走看看