Algorithms are now big factories, foreign companies hard indicators. Development, test, test, always want to go up around the open.
This is today’s daily problem, see is an easy, so do next (unofficial problem solution).
Topic describes
【 array 】 【 sort 】
You are given an array of integers, nums, in which there is always a unique maximum integer. Find the largest element in the array and check that it is at least twice as large as every other number in the array. If so, return the index of the largest element, otherwise -1.Copy the code
Subject address: leetcode-cn.com/problems/la…
The sample
Example 1
Input: nums = [3,6,1,0] output: 1 The index of 6 is 1, so return 1.Copy the code
Example 2
Input: nums = [1,2,3,4] Output: -1 Explanation: 4 is not more than twice as large as 3, so -1 is returned.Copy the code
Example 3
Input: nums = [1] Output: 0 Explanation: The existing number 1 is considered to be at least twice as large as any other number because no other number exists.Copy the code
The problem solving
Since there is always a single largest integer, I first find the largest number in the array and write it down.
Then go through the groups and compare them one by one.
At least twice the number of every other number in the array, which means that when 2 * I > max_num, -1 is returned.
Later, I submitted an error and found that I ignored a problem, that is, when traversing to the maximum number itself is satisfied with the above comparison conditions, and returned -1.
So I added a step, not only the largest number, but also the index of the largest number, and then I remove the largest number, and then I iterate.
If no -1 is returned midway through all traversals, the index of the largest number is returned.
class Solution:
def dominantIndex(self, nums: List[int]) -> int:
max_num = max(nums)
index_max = nums.index(max_num)
nums.remove(max_num)
for i in nums:
if 2 * i > max_num:
return -1
return index_max
Copy the code