1. 程式人生 > >[LeetCode] Largest Number At Least Twice of Others

[LeetCode] Largest Number At Least Twice of Others

max value clas else 無效 給定 number 找到 返回 是否

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

方法1:遍歷一次找出符合條件的元素索引。

這裏存在一個優先級問題:

1、首先判斷當前元素是否為此前所有元素最大值

2、然後判斷當前元素的兩倍是否大於此前找出的最大值

條件1用於選擇最大值,條件2用於判斷條件1選擇的最大值是否符合題意。

在遍歷時判斷當前元素是否為當前的最大元素,如果是則判斷該元素是否為此前最大元素的兩倍。如果是保留當前元素的索引,如果不是此前最大元素的兩倍,令索引值為-1,表示沒有找到符合條件的索引值。

如果某元素的兩倍大於最大值,則說明此前找到的最大值索引無效,令其為-1。

class Solution {
public:
    int dominantIndex(vector<int
>& nums) { int idx = -1; int maxVal = 0; for (int i = 0; i < nums.size(); i++) { // find the max element if (nums[i] > maxVal) { if (nums[i] >= maxVal * 2 ) { idx = i; } else { idx = -1; } // update current max element maxVal = nums[i]; } // judge whether current element is less than twice max value else if (nums[i] * 2 > maxVal) { idx = -1; } } return idx; } }; // 6 ms

方法2:使用map存儲當前元素的索引

先使用map存儲數組對應的索引。

然後對數組從大到小排序

如果此時數組第一個元素大於等於第二個元素的二倍。

則返回此時首元素在原數組中的索引

否則返回-1.

class Solution {
public:
    int dominantIndex(vector<int>& nums) {
        if (nums.size() == 1)
            return 0;
        unordered_map<int, int> m;
        for (int i = 0; i < nums.size(); i++)
            m[nums[i]] = i;
        sort(nums.begin(), nums.end());
        reverse(nums.begin(),  nums.end());
        if (nums[0] >= nums[1] * 2)
            return m[nums[0]];
        else
            return -1;
    }
};
// 9 ms

  

[LeetCode] Largest Number At Least Twice of Others