747. Largest Number At Least Twice of Others

Posted The Tech Road

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了747. Largest Number At Least Twice of Others相关的知识,希望对你有一定的参考价值。

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

class Solution {
public:
    int dominantIndex(vector<int>& nums) {
        if (nums.size() == 0)    return -1;
        int max1 = nums[0], max2, max1index = 0, max2index = -1;
        for (int i = 1; i < nums.size(); i++) {
            if (nums[i] >= max1) {      // we don‘t need to update max1 when it == nums[i] only for this problem
                if (nums[i] > max1) {
                    max2 = max1;
                    max2index = max1index;
                    max1 = nums[i];
                    max1index = i;
                }
            }
            else if (max2index < 0 || nums[i] > max2) {
                max2 = nums[i];
                max2index = i;
            }
        }
        return (max2index < 0 || max1 >= 2 * max2) ? max1index : -1;
    }
};

 

以上是关于747. Largest Number At Least Twice of Others的主要内容,如果未能解决你的问题,请参考以下文章

747. Largest Number At Least Twice of Others

747. Largest Number At Least Twice of Others

[LeetCode] 747. Largest Number At Least Twice of Others

[LeetCode] 747. Largest Number At Least Twice of Others_Easy

747. Largest Number At Least Twice of Others比所有数字都大两倍的最大数

leetcode-747-Largest Number At Least Twice of Others(求vector的最大值和次大值)