领扣LintCode算法问题答案-1053. 至少是其他数字两倍的最大数
发布日期:2021-06-30 17:09:41 浏览次数:4 分类:技术文章

本文共 1240 字,大约阅读时间需要 4 分钟。

领扣LintCode算法问题答案-1053. 至少是其他数字两倍的最大数

目录

1053. 至少是其他数字两倍的最大数

描述

在一个给定的数组nums中,总是存在一个最大元素 。

查找数组中的最大元素是否至少是数组中每个其他数字的两倍。

如果是,则返回最大元素的索引,否则返回-1。

  • nums 的长度范围在[1, 50].
  • 每个 nums[i] 的整数范围在 [0, 99].

样例 1:

输入: nums = [3, 6, 1, 0]输出: 1解释: 6是最大的整数, 对于数组中的其他整数,6大于数组中其他元素的两倍。6的索引是1, 所以我们返回1.

样例 2:

输入: nums = [1, 2, 3, 4]输出: -1解释: 4没有超过3的两倍大, 所以我们返回 -1.

题解

public class Solution {
/** * @param nums: a integer array * @return: the index of the largest element */ public int dominantIndex(int[] nums) {
// Write your code here if (nums.length < 2) {
return 0; } int maxIndex; int secondMaxIndex; if (nums[1] > nums[0]) {
maxIndex = 1; secondMaxIndex = 0; } else {
maxIndex = 0; secondMaxIndex = 1; } for (int i = 2; i < nums.length; i++) {
if (nums[i] > nums[maxIndex]) {
secondMaxIndex = maxIndex; maxIndex = i; } } if (nums[maxIndex] >= nums[secondMaxIndex] * 2) {
return maxIndex; } else {
return -1; } }}

鸣谢

非常感谢你愿意花时间阅读本文章,本人水平有限,如果有什么说的不对的地方,请指正。

欢迎各位留言讨论,希望小伙伴们都能每天进步一点点。

转载地址:https://le-yi.blog.csdn.net/article/details/108809006 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:领扣LintCode算法问题答案-1054. 最少费用的爬台阶方法
下一篇:领扣LintCode算法问题答案-1046. 二进制表示中质数个计算置位

发表评论

最新留言

哈哈,博客排版真的漂亮呢~
[***.90.31.176]2024年04月16日 02时31分45秒