comments | difficulty | edit_url | tags | ||
---|---|---|---|---|---|
true |
Easy |
|
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.
Example 1:
Input: nums = [3,6,1,0] Output: 1 Explanation: 6 is the largest integer. For every other number in the array x, 6 is at least twice as big as x. The index of value 6 is 1, so we return 1.
Example 2:
Input: nums = [1,2,3,4] Output: -1 Explanation: 4 is less than twice the value of 3, so we return -1.
Constraints:
2 <= nums.length <= 50
0 <= nums[i] <= 100
- The largest element in
nums
is unique.
We can traverse the array
We can also first find the maximum value
The time complexity is
class Solution:
def dominantIndex(self, nums: List[int]) -> int:
x, y = nlargest(2, nums)
return nums.index(x) if x >= 2 * y else -1
class Solution {
public int dominantIndex(int[] nums) {
int n = nums.length;
int k = 0;
for (int i = 0; i < n; ++i) {
if (nums[k] < nums[i]) {
k = i;
}
}
for (int i = 0; i < n; ++i) {
if (k != i && nums[k] < nums[i] * 2) {
return -1;
}
}
return k;
}
}
class Solution {
public:
int dominantIndex(vector<int>& nums) {
int n = nums.size();
int k = 0;
for (int i = 0; i < n; ++i) {
if (nums[k] < nums[i]) {
k = i;
}
}
for (int i = 0; i < n; ++i) {
if (k != i && nums[k] < nums[i] * 2) {
return -1;
}
}
return k;
}
};
func dominantIndex(nums []int) int {
k := 0
for i, x := range nums {
if nums[k] < x {
k = i
}
}
for i, x := range nums {
if k != i && nums[k] < x*2 {
return -1
}
}
return k
}
function dominantIndex(nums: number[]): number {
let k = 0;
for (let i = 0; i < nums.length; ++i) {
if (nums[i] > nums[k]) {
k = i;
}
}
for (let i = 0; i < nums.length; ++i) {
if (i !== k && nums[k] < nums[i] * 2) {
return -1;
}
}
return k;
}
/**
* @param {number[]} nums
* @return {number}
*/
var dominantIndex = function (nums) {
let k = 0;
for (let i = 0; i < nums.length; ++i) {
if (nums[i] > nums[k]) {
k = i;
}
}
for (let i = 0; i < nums.length; ++i) {
if (i !== k && nums[k] < nums[i] * 2) {
return -1;
}
}
return k;
};