LeetCode 0747. Largest Number At Least Twice of Others Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
0747. Largest Number At Least Twice of Others

Description

You are given an integer array nums where the largest integer is unique.

Determine 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, or return -1 otherwise.

 

Example 1:

Input: nums = [3,6,1,0]
Output: 1
Explanation: 6 is the largest integer.
For every other number in the array x, 6 is at least 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 is less than twice the value of 3, so we return -1.

 

Constraints:

  • 2 <= nums.length <= 50
  • 0 <= nums[i] <= 100
  • The largest element in nums is unique.

Solutions

Solution 1: Traversal

We can traverse the array nums to find the maximum value x and the second largest value y in the array. If x \ge 2y, then return the index of x, otherwise return -1.

We can also first find the maximum value x in the array and find the index k of the maximum value x at the same time. Then traverse the array again. If we find an element y outside of k that satisfies x < 2y, then return -1. Otherwise, return k after the traversal ends.

The time complexity is O(n), where n is the length of the array nums. The space complexity is O(1).

PythonJavaC++GoTypeScriptJavaScript
class Solution: def dominantIndex(self, nums: List[int]) -> int: x, y = nlargest(2, nums) return nums.index(x) if x >= 2 * y else -1(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !