码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Largest Number At Least Twice of Others

时间:2018-01-03 22:36:41      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:大于   说明   anti   not   begin   exp   tor   end   mina   

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

标签:大于   说明   anti   not   begin   exp   tor   end   mina   

原文地址:https://www.cnblogs.com/immjc/p/8185540.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!