1. 程式人生 > >747. Largest Number At Least Twice of Others比所有數字都大兩倍的最大數

747. Largest Number At Least Twice of Others比所有數字都大兩倍的最大數

play pre color 什麽 PE open pac ice The

[抄題]:

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

747. Largest Number At Least Twice of Others比所有數字都大兩倍的最大數