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.
在一个给定的整数数组nums中,总存在一个最大的数
找到这个最大的数,检查其是否至少是nums中其他每个元素的两倍以上
如果是,返回这个最大元素的索引,否则返回-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]
.
Solutions:
Python
'''
思路很简单,(1)对数组降序排序,如果最大的数大于等于第二大的数的二倍就直接返回最大数的index,否则返回-1
'''
(1)
class Solution:
def dominantIndex(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 1:
return 0
numscopy = sorted(nums,reverse = True)
if numscopy[0] >= 2*numscopy[1]:
return nums.index(numscopy[0])
return -1
(2)
'''
先找到nums中最大的数,遍历排除最大数的nums,如果不满足条件直接返回-1,否则返回最大数index
'''
class Solution:
def dominantIndex(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
max_e = max(nums)
index = nums.index(max_e)
nums.remove(max_e)
for i in nums:
if max_e < 2*i:
return -1
return index
C++
(1)
/*
忍不住要吐槽一下,C++虽然很快,但是比起Python真的麻烦好多啊
算法思想和Python差不多,需要注意的就是C++中vector的用法,查找最大元素得到的maxnum是一个迭代器
要取得这个最大元素的值需要加*号:*maxnum,取其距离用maxnum-nums.begin()
*/
class Solution {
public:
int dominantIndex(vector<int>& nums) {
vector<int>::iterator maxnum = max_element(nums.begin(),nums.end());
int index = maxnum - nums.begin();
int size = nums.size();
if (size == 1){
return 0;
}
for (int i = 0;i<size;i++){
if (*maxnum == nums[i]){
continue;
}
else if (*maxnum < 2*nums[i]){
return -1;
}
else{
continue;
}
}
return index;
}
};
(2)
class Solution {
public:
int dominantIndex(vector<int>& nums) {
int max = nums[0];
int flag = 0;
for (int i = 1; i < nums.size(); i++) { //寻找nums中的最大值和最大值的index
if (max < nums[i]){
max = nums[i];
flag = i;
}
}
for (int i = 0; i < nums.size(); i++) { //判断条件是否符合
if (nums[i] > max/2 && i != flag ) {
flag = -1;
}
}
return flag;
}
};
C++中找到最大值的方法: