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

     [暴力解法]:

    时间分析:

    空间分析:

     [优化后]:

    时间分析:

    空间分析:

    [奇葩输出条件]:

    [奇葩corner case]:

    数组应该考虑到只有一位数的情况

    [思维问题]:

    [一句话思路]:

    [输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

    [画图]:

    [一刷]:

    1. "至少2倍"相当于>=

    [二刷]:

    [三刷]:

    [四刷]:

    [五刷]:

      [五分钟肉眼debug的结果]:

    [总结]:

    1. 数组应该考虑到只有一位数的情况

    [复杂度]:Time complexity: O(n) Space complexity: O(1)

    [英文数据结构或算法,为什么不用别的数据结构或算法]:

    [关键模板化代码]:

    [其他解法]:

    [Follow Up]:

    [LC给出的题目变变变]:

    414三位数

     [代码风格] :

    class Solution {
        public int dominantIndex(int[] nums) {
            //cc
            if (nums == null || nums.length == 0) {
                return -1;
            }
            if (nums.length == 1) {
                return 0;
            }
            
            //ini
            int max2 = Integer.MIN_VALUE, max1 = Integer.MIN_VALUE + 1, index = 0;
            
            //for loop, change max1 max2 
            for (int i = 0; i < nums.length; i++) {
                if (nums[i] > max1) {
                    max2 = max1;
                    max1 = nums[i];
                    index = i;
                }else if (nums[i] > max2) {
                    max2 = nums[i];
                }
            }
            
            //return
            return (max1 >= 2 * max2) ? index : -1;
        }
    }
    View Code
  • 相关阅读:
    ObjectiveC 日记⑦ 内存管理
    Jquery自定义分页插件
    C#中的静态类和静态成员
    多线程访问共同的代码或者对象:lock避免出错
    wordpress绑定新浪微博
    组态软件基础知识概述
    书籍推荐:《网站运营直通车:7天精通SEO》
    wordpress代码高亮插件推荐:AutoSyntaxHighlighter
    书籍推荐:《伟大是熬出来的:冯仑与年轻人闲话人生》
    wince平台用xml文件做配置文件
  • 原文地址:https://www.cnblogs.com/immiao0319/p/8905714.html
Copyright © 2011-2022 走看看