Largest Number At Least Twice of Others

In a given integer array nums, there is always exactly one largest element.

Find whether the largest element in the array is at least twice as much as every other number in the array.

If it is, return the index of the largest element, otherwise return -1.

Example 1: Input: nums = [3, 6, 1, 0] Output: 1 Explanation: 6 is the largest integer, and for every other number in the array x, 6 is more than twice as big as x. The index of value 6 is 1, so we return 1.

Solution : Using two loops

Scan through the array to find the unique largest element m, keeping track of it’s index maxIndex. Scan through the array again. If we find some x != m with m < 2*x, we should return -1. Otherwise, we should return maxIndex.

int dominantIndex(vector<int>& nums) {
    if(nums.empty()) return -1;
    int maxItem = INT_MIN, maxTwice = INT_MIN, index = -1;
    for(int i=0; i<nums.size(); i++) {
        if(maxItem < nums[i]) {
            maxItem = nums[i];
            index = i;
        }
    }

    for(int i=0; i<nums.size(); i++) {
        if(i != index) maxTwice = max(maxTwice, 2 * nums[i]);
    }

    return maxItem < maxTwice ? -1 : index;
}

Solution : Using only one loop to find the largest and second largest number

We can use one loop to find the largest and second largest number in the array.

int dominantIndex(vector<int>& nums) {
    int first = INT_MIN, second = INT_MIN, index = 0;
    for (int i=0; i < nums.size(); i++) {
        if (nums[i] > first) {
            second = first;
            first = nums[i];
            index = i;
        } else if (nums[i] > second) {
            second = nums[i];
        }
    }
    return first >= second * 2 ? index : -1;
}

results matching ""

    No results matching ""