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.
我想的一个方法,自己理一下思路。
不断记录最大值和第二大值,只要最大值是第二大值的两倍以上,就满足题目要求。
设定变量f和s来记录最大值和第二大值的位置,同时tempf和temps来记录中间出现的最大值和第二大值。
从将f和s设定为第一个数值开始。
从第二个数开始扫描。
1、比f位置处的数大的,那就是新的f
2、比f位置处的数小而比s处的大,就是新的s
3、同时f和s错开
最后f==s,那么只有一个数,返回0位置
最后f处的数大于(2*s处的数-1),那么返回f
不然就是没有这个数,返回-1
class Solution {
public:
int dominantIndex(vector<int>& nums) {
int s=0,f=0,tempf=0,temps=0;
for(int i=1;i<nums.size();i++)
{
if(nums[i]>nums[f]) tempf=i,temps=f;
else if((nums[i]>nums[s])&&(nums[i]<nums[f])) temps=i;
else if (s==f) temps=i;
f=tempf;s=temps;
}
if(s==f) return 0;
if(nums[f]>2*nums[s]-1) return f;
else return -1;
}
浙公网安备 33010602011771号