每日一题 leetcode 747. 至少是其他数字两倍的最大数 java题解

阅读 33

2022-01-13

题目

https://leetcode-cn.com/problems/largest-number-at-least-twice-of-others/

代码

class Solution {
    public int dominantIndex(int[] nums) {
        int len=nums.length;
        int first=nums[0];
        int second=Integer.MIN_VALUE;
        int firstIndex=0,secondIndex=-1;
        for(int i=1;i<len;i++){
            if(nums[i]>first){
                second=first;//第二大
                first=nums[i];//最大
                secondIndex=firstIndex;
                firstIndex=i;
            }
            else if(nums[i]>second){
                second=nums[i];
                secondIndex=i;
            }
        }
        if(first>=2*second){
            return firstIndex;
        }
        else{
            return -1;
        }
    }
}

精彩评论(0)

0 0 举报