zoukankan      html  css  js  c++  java
  • 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.

    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].
     1 class Solution {
     2     public int dominantIndex(int[] nums) {
     3         int bigger = -1;
     4         boolean moreThanTwice = false;
     5         
     6         int index = -1;
     7         for(int i = 0; i < nums.length; i++) {
     8             if (nums[i] > bigger) {
     9                 index = i;
    10                 moreThanTwice = (nums[i] >= bigger * 2);
    11                 bigger = nums[i];
    12             } else if (bigger < nums[i] * 2) {
    13                 moreThanTwice = false;
    14             }
    15         }
    16         
    17         return moreThanTwice ? index : -1;
    18     }
    19 }
     1 class Solution {
     2     public int dominantIndex(int[] nums) {
     3         int num1 = nums[0], num2 = Integer.MIN_VALUE; // max number, second largest number
     4         
     5         int index = 0;
     6         for (int i = 1; i < nums.length; i++) {
     7             if (nums[i] > num1) {
     8                 num2 = num1;
     9                 num1 = nums[i];
    10                 index = i;
    11             } else if (nums[i] > num2) {
    12                 num2 = nums[i];
    13             }
    14         }
    15         
    16         return num1 >= num2 * 2 ? index : -1;
    17     }
    18 }
  • 相关阅读:
    1.ok6410移植bootloader,移植u-boot,学习u-boot命令
    ok6410按键中断编程,linux按键裸机
    四. jenkins部署springboot项目(1)--window环境
    一.jenkins安装(windows环境)
    oracle服务端导出/导入方式expdp/impdp
    linux 日志文件查看
    linux kafka进程挂了 自动重启
    kafka manager遇到的一些问题
    if条件语句
    shell脚本的条件测试与比较
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/9110374.html
Copyright © 2011-2022 走看看