[leetcode-748-Largest Number At Least Twice of Others]
2024-08-29 16:01:22
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]
.
思路:
扫描一遍数组,记录最大值与第二大的值,如果最大的是第二大的两倍以上,那么返回索引即可。
int dominantIndex(vector<int>& nums)
{
int len = nums.size();
int biggest = ,second = ,index = ; for(int i=;i<len;i++)
{
if(nums[i]>biggest)
{
second = biggest;
biggest = nums[i];
index = i;
}
else if(nums[i]>second)
{
second = nums[i];
}
}
if(biggest>=second*)return index;
else return -;
}
最新文章
- 关于WCF报错之调用方未由服务器进行身份验证
- 004_URL 路由 - 定制路由系统 &; 使用区域
- RecyclerView (一) 基础知识
- OA系统部门结构树
- cygwin如何断点续传
- python-Pickle序列化
- IOS 音频播放
- 如何将一个Jsp网站打包发布(发布为War文件)
- Codeforces348C - Subset Sums
- 一 Django模型层简介(一)
- CentOS Ubantu linux中实用系统相关常用命令
- 【HDU4751】Divide Groups
- mysql数据库授权
- 再也不用担心面试官问你HashCode和equals了
- 【转】win中IDLE选择virtualenv的启动方法
- linux下git远程仓库的搭建
- 资源 | 源自斯坦福CS229,机器学习备忘录在集结
- jQuery照片墙相册
- openwrt设置uboot环境变量在flash上的存储地址
- sqoop导数