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 _theindex of the largest element, or return _-1otherwise.
Input: nums =[3,6,1,0]Output: 1Explanation: 6is the largest integer.For every other number in the array x,6is at least twice as big as x.The index of value 6is1, so we return1.
To check if the largest number is at least twice every other, find the largest and second largest numbers. If the largest is at least twice the second largest, return its index; otherwise, return -1.
classSolution {
fundominantIndex(nums: IntArray): Int {
var mx = -1var smx = -1var idx = -1for (i in nums.indices) {
if (nums[i] > mx) { smx = mx; mx = nums[i]; idx = i }
elseif (nums[i] > smx) smx = nums[i]
}
returnif (mx >=2 * smx) idx else -1 }
}
1
2
3
4
5
6
7
8
9
10
classSolution:
defdominantIndex(self, nums: list[int]) -> int:
mx = smx =-1 idx =-1for i, v in enumerate(nums):
if v > mx:
smx, mx, idx = mx, v, i
elif v > smx:
smx = v
return idx if mx >=2* smx else-1
1
2
3
4
5
6
7
8
9
10
impl Solution {
pubfndominant_index(nums: Vec<i32>) -> i32 {
let (mut mx, mut smx, mut idx) = (-1, -1, -1);
for (i, &v) in nums.iter().enumerate() {
if v > mx { smx = mx; mx = v; idx = i asi32; }
elseif v > smx { smx = v; }
}
if mx >=2* smx { idx } else { -1 }
}
}