747. Largest Number At Least Twice of Others*
https://leetcode.com/problems/largest-number-at-least-twice-of-others/description/
题目描述
In a given integer array nums
, there is always exactly one largest element.
Find 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, otherwise return -1
.
Example 1:
Input: nums = [3, 6, 1, 0]
Output: 1
Explanation: 6 is the largest integer, and for every other number in the array x,
6 is more than 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 isn't at least as big as twice the value of 3, so we return -1.
Note:
nums
will have a length in the range[1, 50]
.- Every
nums[i]
will be an integer in the range[0, 99]
.
解题思路
找到这个数组中最大的两个数 first(第一大的数)以及 second(第二大的数), 然后判断 first 是否是 second 的两倍即可.
C++ 实现 1
class Solution {
public:
int dominantIndex(vector<int>& nums) {
if (nums.size() < 2) return nums.empty() ? -1 : 0;
int first = nums[0] >= nums[1] ? 0 : 1;
int second = nums[0] < nums[1] ? 0 : 1;
for (int i = 2; i < nums.size(); ++i) {
// 当找到比 nums[first] 大的元素时, 不要忘了更新 second.
if (nums[i] > nums[first]) {
second = first;
first = i;
}
else if (nums[i] > nums[second])
second = i;
}
return nums[first] >= 2 * nums[second] ? first : -1;
}
};
C++ 实现 2
两年前的实现
class Solution {
public:
int dominantIndex(vector<int>& nums) {
// 如果数组中只有一个数, 那么返回 true
int imax = nums[0];
int isec = INT32_MIN;
int index = 0;
for (int i = 1; i < nums.size(); ++i) {
if (nums[i] > imax) {
isec = imax;
imax = nums[i];
index = i;
}
else if (nums[i] > isec) {
isec = nums[i];
}
}
return imax >= 2 * isec ? index : -1;
}
};