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

 

posted @ 2018-04-06 22:41  bonelee  阅读(336)  评论(0编辑  收藏  举报