Largest Number At Least Twice of Others
Problem
You are given an integer array nums
where the largest integer is unique.
Determine 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, or return -1
otherwise.
Constraints
2 <= nums.length <= 50
0 <= nums[i] <= 100
- The largest element in
nums
is unique.
Solution
The problem Largest Number At Least Twice of Others
can be solved using a priority queue with a capacity of 2 to find the first and second largest elements from the given array.
Implementation
static const int fast_io = []()
{
std::ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
return 0;
}();
typedef pair<int, int> Pair;
class Solution
{
public:
int dominantIndex(vector<int> &nums)
{
priority_queue<Pair, vector<Pair>, greater<Pair>> pq;
for (int i = 0; i < nums.size(); i++)
{
pq.push(make_pair(nums[i], i));
if (pq.size() == 3)
pq.pop();
}
pair<int, int> second = pq.top();
pq.pop();
pair<int, int> first = pq.top();
return second.first * 2 <= first.first ? first.second : -1;
}
};