在一个给定的数组nums
中,总是存在一个最大元素 。
查找数组中的最大元素是否至少是数组中每个其他数字的两倍。
如果是,则返回最大元素的索引,否则返回-1。
示例 1:
输入: nums = [3, 6, 1, 0] 输出: 1 解释: 6是最大的整数, 对于数组中的其他整数, 6大于数组中其他元素的两倍。6的索引是1, 所以我们返回1.
示例 2:
输入: nums = [1, 2, 3, 4] 输出: -1 解释: 4没有超过3的两倍大, 所以我们返回 -1.
提示:
nums
的长度范围在[1, 50]
.- 每个
nums[i]
的整数范围在[0, 100]
.
解决思路:一次遍历找出最大数和次大数,若最大数至少是次大数的两倍,返回最大数下标,否则返回-1;
int dominantIndex(int* nums, int numsSize){
if (1 == numsSize)
return 0;
int max = -1;
int second_max = -1;
int cursor = 0;
int cursor_of_max = 0;
for (cursor=0; cursor<numsSize; cursor++)
{
if (nums[cursor] >= max)
{
second_max = max;
max = nums[cursor];
cursor_of_max = cursor;
}
else if (nums[cursor] >= second_max )
{
second_max = nums[cursor];
}
}
if (max >= second_max*2)
return cursor_of_max;
return -1;
}