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 }
  • 相关阅读:
    k8s dashboard 配置使用kubeconfig文件登录
    Spring Cloud 专题之七:Sleuth 服务跟踪
    Spring Cloud 专题之六:bus 消息总线
    Spring Cloud专题之五:config 配置中心
    Docker Storage Driver:存储驱动
    Docker引擎升级教程
    Docker介绍及安装详解
    Autowired和Resource的区别和联系
    OLTP与OLAP
    转载-JAVA 关于JNI本地库加载
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/9110374.html
Copyright © 2011-2022 走看看