원문)
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.
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.
번역)
정수 배열이 주어지고, 그곳에는 가장 큰 요소가 있다.
해당 가장 큰 요소는 그 다음 큰 수의 두배가 넘어야 한다.
만약 있다면 그 해당 index를 반환하고 아니라면 -1를 반환하라.
예제)
문제접근)
코드)
1. 접근
2. 접근
해당 가장 큰 요소는 그 다음 큰 수의 두배가 넘어야 한다.
만약 있다면 그 해당 index를 반환하고 아니라면 -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:
nums
will have a length in the range[1, 50]
.- Every
nums[i]
will be an integer in the range[0, 99]
.
- 리스트를 하나 복사해두고 max하나 최대값 빼고 다음 max값구해서
m1, m2를 구하고 원본 리스트에서 index를 구하여 계산한다. - 리스트를 복사하는것이 마음에 걸려서 조금더 찾아보니
최대값을 구해두고 그 값을 이용하여 index를 구하고 나머지들끼리 max를 구한다.
코드)
1. 접근
class Solution: def dominantIndex(self, nums: List[int]) -> int: if len(nums) < 2: return 0 tmp = nums.copy() m1 = max(tmp) tmp.remove(m1) m2 = max(tmp) index = nums.index(m1) if m1 >= m2 * 2: return index else: return -1
2. 접근
class Solution: def dominantIndex(self, nums: List[int]) -> int: m1 = max(nums) m2 = 0 index = -1 l = len(nums) for i in range(l): if nums[i] == m1: index = i else: m2 = max(m2, nums[i]) if m1 >= m2 * 2: return index else: return -1
댓글 없음:
댓글 쓰기