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:

  1. nums will have a length in the range [1, 50].
  2. 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 -;
}

最新文章

  1. 关于WCF报错之调用方未由服务器进行身份验证
  2. 004_URL 路由 - 定制路由系统 &amp; 使用区域
  3. RecyclerView (一) 基础知识
  4. OA系统部门结构树
  5. cygwin如何断点续传
  6. python-Pickle序列化
  7. IOS 音频播放
  8. 如何将一个Jsp网站打包发布(发布为War文件)
  9. Codeforces348C - Subset Sums
  10. 一 Django模型层简介(一)
  11. CentOS Ubantu linux中实用系统相关常用命令
  12. 【HDU4751】Divide Groups
  13. mysql数据库授权
  14. 再也不用担心面试官问你HashCode和equals了
  15. 【转】win中IDLE选择virtualenv的启动方法
  16. linux下git远程仓库的搭建
  17. 资源 | 源自斯坦福CS229,机器学习备忘录在集结
  18. jQuery照片墙相册
  19. openwrt设置uboot环境变量在flash上的存储地址
  20. sqoop导数

热门文章

  1. html中的居中问题
  2. git 的一些基本命令小结
  3. 解决 ajax 跨域
  4. (七)json序列化
  5. 分布式缓存 Redis(二)
  6. mysql 主主架构,多入口 互为备份
  7. 大数据学习--day06(Eclipse、数组)
  8. Scala 语法(一)
  9. 利用 Python 插件 xlwings 读写 Excel
  10. python拓展应用:运行do文件及其衍生内容