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

    题目:

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

    查找数组中的最大元素是否至少是数组中每个其他数字的两倍。

    如果是,则返回最大元素的索引,否则返回-1。

    提示:

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

    好消息,我终于可以自己完成一题了,虽然有点偷鸡

    class Solution:
        def dominantIndex(self, nums: List[int]) -> int:
            if(len(nums)==1):
                return 0
            max1=0
            max2=0
            max1=max(nums)
            a=nums.index(max1)
            num=nums
            num.pop(a)
            max2=max(num)
            if(max1>=2*max2):
                return a
            return -1
    执行用时 : 96 ms, 在Largest Number At Least Twice of Others的Python3提交中击败了7.30% 的用户
    内存消耗 : 13.3 MB, 在Largest Number At Least Twice of Others的Python3提交中击败了12.06% 的用户
    虽然很惨,但是还是很高兴哈哈哈哈
     
      借鉴一下别人的
    int dominantIndex(int* nums, int numsSize) {
        int max;
        int sec;
        int idx;
        int i;
            
        if(0 == numsSize){
            return -1;
        }    
        if(1 == numsSize){
            return 0;
        }
        
        if(nums[0]>nums[1]){
            max = nums[0];
            sec = nums[1];
            idx = 0;
        }else{
            max = nums[1];
            sec = nums[0];
            idx = 1;
        }
        
        
        for(i=2; i<numsSize;i++){        
            if(nums[i]>max){  
                sec = max;
                max = nums[i];
                idx = i;
            }else if(nums[i]>sec){
                sec = nums[i];
            }
        }     
        
        return (max/2>=sec)?idx:-1;
    }

    不得不说,c的效率还是高啊。。。

  • 相关阅读:
    vue 文件分段上传
    深度clone
    js 导出excel
    js 校验
    设计模式原则
    多态
    数据库sql
    Redis快速入门
    C#中使用Redis学习二 在.NET4.5中使用redis hash操作
    在c#中使用servicestackredis操作redis
  • 原文地址:https://www.cnblogs.com/dmndxld/p/10787222.html
Copyright © 2011-2022 走看看