747. Largest Number At Least Twice of Others

406 篇文章 0 订阅
406 篇文章 0 订阅

1,题目要求
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.
这里写图片描述
也就是找到数组中最大的数字,如果它比其他所有的数字都要大两倍及以上,则返回其索引值;否则就返回-1。

2,题目思路
题目的要求进行简化,就是找到整个数组中最大的数字和第二大的数字,看最大的是否是第二大的两倍及以上,如果是则返回索引,不是就返回-1;
对于找到这两个数字,其实可以直接用两次for循环来进行暴力查找,时间复杂度为O(n),可以达到题目要求。不过可以进行整合,如果num[i]比最大值大,就更新最大值和第二大的值,并记录最大值的索引。否则,如果num[i]比第二大的值大,则直接更新第二大的值即可。

3,程序源码

class Solution {
public:
    int dominantIndex(vector<int>& nums) {
        int max = 0;
        int maxIndex = 0;
        int secondMax=0;
        for(int i=0;i<nums.size();i++)
        {
            if(nums[i]>max)
            {
                secondMax = max;
                max = nums[i];
                maxIndex = i;
            }
            else if(nums[i]>secondMax)
            {
                secondMax = nums[i];
            }
        }        
        return (max/2>=secondMax)?maxIndex:-1;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值