LeetCode747. Largest Number At Least Twice of Others

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:

1
2
3
4
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:

1
2
3
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:

  1. nums will have a length in the range [1, 50].
  2. Every nums[i] will be an integer in the range [0, 99].

Hints:

  • Scan through the array to find the unique largest element m, keeping track of it’s index maxIndex.
  • Scan through the array again.
  • If we find some x != m with m < 2*x, we should return -1.
  • Otherwise, we should return maxIndex.

my code in c++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
int dominantIndex(vector<int>& nums) {
int m = nums[0];
int index = 0;//1.
for (int i=0;i<nums.size();i++)
{
if (m < nums[i])
{
index = i;
m = nums[i];
}
}

for (auto const & num : nums)
{
if (num != m&&num * 2>m)
return -1;
}
return index;
}
};

细节

  1. 要返回的是index,不是max,所以要记录maxindex。

总结

  • O(n^2)time,O(1)space

  • O(n)找到最大数,并记录索引,一定要记录索引啊!!因为要返回的是index!

  • O(n)重新遍历,如果发现有 x!=m 且 2x>m,返-1
Thanks for Support.