C++ O(n) one pass


  • 0
    class Solution {
    public:
        int dominantIndex(vector<int>& nums) {
            if (nums.size() < 2) return -1;
            int index = 0, high = nums[0];
            for (int i = 1; i < nums.size(); i++) {
                if (nums[i] == high) continue;
                int tmp = high;
                high = max(high, nums[i]);
                if (high == nums[i]) {
                    if (nums[i] < 2 * tmp) return -1;
                    index = i;
                } else {
                    if (high < 2 * nums[i]) return -1;
                }
            }
            return index;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.