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;
    }
};
原文地址:https://www.cnblogs.com/JTechRoad/p/8976010.html