747. Largest Number At Least Twice of Others

题目分析

题目链接,登录 LeetCode 后可用
这道题让我们判断一个数组中最大的值是否至少是其他任何数的两倍。这里用到的思路是找出数组中的最大值和第二大值即可。

代码

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

你可能感兴趣的:(747. Largest Number At Least Twice of Others)