Leetcode 747——Largest Number At Least Twice of Others(最大数至少是其他数字的两倍)

博客分类: Leetcode 刷题笔记 阅读次数: 102 次

Leetcode 747——Largest Number At Least Twice of Others(最大数至少是其他数字的两倍)

题目描述

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. 遍历一遍数组 nums,找出最大的数字 max 以及它对应的下标 index 并记录下来。
  2. 重新遍历数组,如果我们找到数组中有元素满足 i != index2 * nums[i] > max ,则返回 -1 ,否则,我们返回 index

参考代码

//C++
class Solution {
public:
	int dominantIndex(vector<int>& nums) 
	{
		int max = nums[0], index = 0;
		for (int i = 1; i < nums.size(); i++)
		{
			if (max < nums[i])
			{
				max = nums[i];
				index = i;
			}
		}
		for (int i = 0; i < nums.size(); i++)
		{
			if (max < nums[i] * 2 && i != index)
				return -1;
		}
		return index;
	}
};