【Leetcode_easy】747. Largest Number At Least Twice of Others

problem

747. Largest Number At Least Twice of Others

题意:

solution1:

class Solution {
public:
    int dominantIndex(vector<int>& nums) {
        int mx = -1, secondMx = -1, mxId = -1;//err...
        if(nums.size()<0) return -1;
        for(int i=0; i<nums.size(); i++)
        {
            if(nums[i]>mx)
            {
                secondMx = mx;
                mx = nums[i];
                mxId = i;
            }
            else if(nums[i]>secondMx) secondMx = nums[i];
        }
        return (2*secondMx<=mx) ? mxId : -1;   
    }
};

solution2:

class Solution {
public:
    int dominantIndex(vector<int>& nums) {
        int mx = INT_MIN, mxId = -1;//err...
        if(nums.size()<0) return -1;
        for(int i=0; i<nums.size(); i++)
        {
            if(nums[i]>mx) { mx = nums[i]; mxId = i; }
        }
        for(auto num:nums)
        {
            if(mx!=num && mx-num<num) return -1;
        }
        return mxId;   
    }
};

参考

1. Leetcode_easy_747. Largest Number At Least Twice of Others;

2. Grandyang;

3. Discuss;

原文地址:https://www.cnblogs.com/happyamyhope/p/11171591.html