Leetcode 747: Largest Number At least Twice of Others

问题描述:
You are given an integer array nums where the largest integer is unique.
Determine 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, or return -1 otherwise.
一个数组有唯一的最大的元素,判断最大的元素是否是其他的元素的2倍大

思路:
最简单直接的思路就是,找出最大值和第二大的值,然后比较就是了

代码如下:
以下这一段代码其实还可以优化,找最值的同时也在记录index,不用过两遍循环

class Solution {
    public int dominantIndex(int[] nums) {
        int largest=-1;
        int second_largest=-1;
        for(int i=0; i<nums.length; i++){
            if(nums[i]>=largest){
                second_largest=largest;
                largest=nums[i];
            }
            if((nums[i]>second_largest)&&(nums[i]<largest)){
                second_largest=nums[i];
            }
        }
        if(largest>=(second_largest*2)){
            for(int i=0; i<nums.length; i++){
                if(nums[i]==largest)  return i;
            }
            return -1;
        }
        else{
            return -1;
        }
    }
}

时间复杂度: O(n)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值