class Solution:
def dominantIndex(self, nums):
if not nums:
return -1
max_num = max(nums)
max_index = nums.index(max_num)
for i, n in enumerate(nums):
if i != max_index and max_num < 2 * n:
return -1
return max_index
class Solution {
public:
int dominantIndex(vector<int>& nums) {
if (nums.empty()) return -1;
int max_num = -1, max_index = -1;
for (int i = 0; i < nums.size(); ++i) {
if (nums[i] > max_num) {
max_num = nums[i];
max_index = i;
}
}
for (int i = 0; i < nums.size(); ++i) {
if (i != max_index && max_num < 2 * nums[i]) {
return -1;
}
}
return max_index;
}
};
class Solution {
public int dominantIndex(int[] nums) {
if (nums.length == 0) return -1;
int maxNum = -1, maxIndex = -1;
for (int i = 0; i < nums.length; i++) {
if (nums[i] > maxNum) {
maxNum = nums[i];
maxIndex = i;
}
}
for (int i = 0; i < nums.length; i++) {
if (i != maxIndex && maxNum < 2 * nums[i]) {
return -1;
}
}
return maxIndex;
}
}
var dominantIndex = function(nums) {
if (nums.length === 0) return -1;
let maxNum = -1, maxIndex = -1;
for (let i = 0; i < nums.length; i++) {
if (nums[i] > maxNum) {
maxNum = nums[i];
maxIndex = i;
}
}
for (let i = 0; i < nums.length; i++) {
if (i !== maxIndex && maxNum < 2 * nums[i]) {
return -1;
}
}
return maxIndex;
};
You are given an array of integers called nums
. Your task is to find whether the largest number in the array is at least twice as large as every other number in the array. If it is, return the index of the largest number. If it is not, return -1
.
-1
.At first glance, the problem seems to require comparing the largest number to all other numbers in the array. A brute-force approach would be to check, for each element, if it is the largest and then see if it is at least twice every other number. However, since there is always a unique largest element, we can optimize by first finding the largest, and then verifying the "at least twice" condition against the rest.
This means we don't need to check each element as a candidate for "largest"—we only need to find the largest, and then check if it is at least twice as large as all others. This speeds up our process and avoids unnecessary comparisons.
-1
.We use two passes over the array: one to find the largest, and one to check the condition. This is more efficient than nested loops and ensures clarity in logic.
Let's use the sample input nums = [3, 6, 1, 0]
:
6
at index 1
is the largest.6 >= 2*3
? Yes, 6 >= 6
.6 >= 2*1
? Yes, 6 >= 2
.6 >= 2*0
? Yes, 6 >= 0
.1
.
If we try nums = [1, 2, 3, 4]
:
4
at index 3
.4 >= 2*3
? 4 < 6
— fails!-1
.The optimized approach is much faster and more scalable for large arrays.
This problem is elegantly solved by first identifying the largest element, then validating its dominance by comparing it to every other element. The two-pass method is efficient and easy to understand, avoiding unnecessary complexity. The key insight is realizing that only the largest element needs to be checked, thanks to the problem's constraints.