zoukankan      html  css  js  c++  java
  • 747. 至少是其他数字两倍的最大数

    在一个给定的数组nums中,总是存在一个最大元素 。

    查找数组中的最大元素是否至少是数组中每个其他数字的两倍。
    如果是,则返回最大元素的索引,否则返回-1。

    • 示例 1:

    输入: nums = [3, 6, 1, 0]
    输出: 1
    解释: 6是最大的整数, 对于数组中的其他整数,
    6大于数组中其他元素的两倍。6的索引是1, 所以我们返回1.

    • 示例 2:

    输入: nums = [1, 2, 3, 4]
    输出: -1
    解释: 4没有超过3的两倍大, 所以我们返回 -1.

    • 提示:

    nums 的长度范围在[1, 50].
    每个 nums[i] 的整数范围在 [0, 99].

    • 分析:

    可以不用每次遍历列表中的元素去判断是否 num*2 <= Max(num),
    只需要找到整个列表中第二大的元素,若该元素满足上述条件,即可返回最大元素索引

    • 解法1:
    class Solution(object):
        def dominantIndex(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            max_num = max(nums)
            num_list = []
            if len(nums) == 1:
                return 0
            for num in nums:
                if num * 2 <= max_num:
                    num_list.append(num)
            if len(num_list) == len(nums)-1:
                return nums.index(max_num)
            else:
                return -1
    
    
    • 解法2:
    class Solution(object):
        def dominantIndex(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            if len(nums) == 1:
                return 0
            Max = max(nums)
            indexs = nums.index(Max)
            nums.pop(indexs)
            second_max = max(nums)
            if Max >= 2*second_max:
                return indexs
            else:
                return -1
    
    
    • 解法3:
    class Solution(object):
        def dominantIndex(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            highest = -1
            second_highest = -1
            nums_index = 0
    
            for index, num in enumerate(nums):
                if num >= highest:
                    second_highest = highest
                    highest = num
                    nums_index = index
                elif num > second_highest:
                    second_highest = num
            if highest < second_highest*2:
                return -1
            return nums_index
    
    

    总结:
    三种解法的时间复杂度相同,但对比下来,第三种解法较少的使用了python内置函数

  • 相关阅读:
    最近比较忙
    堆栈的实现
    推荐一款开源优秀Javascript编辑器Aptana Studio
    OOJ面向对象编程的三大特点封装,继承,多态分析与实例
    ASP.NET设计模式之单体模式Singleton
    OOJ面向对象的JAVASCRIPT(一)
    【转】性能优化关于Asp.net性能的技巧
    性能优化关于JQuery的性能优化
    学习javascript的动态this指针与动态绑定 call与apply函数的应用
    OOJ面向对象的JAVASCRIPT(二)
  • 原文地址:https://www.cnblogs.com/AimeeCodeWorld/p/10802762.html
Copyright © 2011-2022 走看看