Leetcode 747. Largest Number At Least Twice of Others Certainly! Let’s break down the problem step by step.
You are given an array of integers nums
where the largest integer is at least twice as large as every other number in the array. If this condition holds true, return the index of the largest number, otherwise return -1.
Let’s move forward assuming typical constraints:
nums
will contain at least one integer.Here’s the C++ code implementing the above strategy:
#include <vector>
#include <iostream>
#include <algorithm>
#include <limits.h>
using namespace std;
class Solution {
public:
int dominantIndex(vector<int>& nums) {
if (nums.size() == 1) {
return 0; // If there's only one number, it's trivially the largest.
}
int maxIndex = 0;
int maxVal = INT_MIN;
int secondMaxVal = INT_MIN;
// Find maximum and second maximum values
for (int i = 0; i < nums.size(); ++i) {
if (nums[i] > maxVal) {
secondMaxVal = maxVal; // Update second maximum
maxVal = nums[i]; // Update maximum
maxIndex = i; // Update index of maximum
} else if (nums[i] > secondMaxVal) {
secondMaxVal = nums[i]; // Update second maximum
}
}
// Check the condition
if (maxVal >= 2 * secondMaxVal) {
return maxIndex;
} else {
return -1;
}
}
};
int main() {
Solution sol;
vector<int> nums = {3, 6, 1, 0};
cout << "Dominant Index: " << sol.dominantIndex(nums) << endl; // Output: 1
return 0;
}
This solution is efficient and straightforward, ensuring that the condition is verified in a single iteration over the array, resulting in an optimal time complexity.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?