오늘도 개발

16. Largest Number At Least Twice of Others 본문

자료구조 & 알고리즘/Leetcode

16. Largest Number At Least Twice of Others

Sueeeeeee 2022. 9. 14. 22:17

문제

https://leetcode.com/explore/learn/card/array-and-string/201/introduction-to-array/1147/

주어진 배열의 가장 큰 숫자가 다른 모든 숫자의 최소 2배가 되는지 확인,

2배가 넘는다면 가장 큰 숫자의 인덱스 반환. 넘지 않는다면 -1 반환.

가장 큰 숫자는 하나만 존재한다고 가정.

Input: nums = [3,6,1,0]
Output: 1

 

내가 생각한 해결 방식

최대값과 최대값의 인덱스 구하기.

for문으로 iterate하며 각 요소에 2를 곱해서 결과 확인.

 

time complexity는 O(n) : 최대값 구할 때 iteration 1회, 최대값 인덱스 구할 때 iteration 1회, for 문에서 iteration 1회

def dominantIndex(nums):
    # 최대값 구하기
    maxValue = max(nums)
    # 최대값의 인덱스 구하기
    maxIndex = nums.index(maxValue)

    for num in nums:
        # 최대값이 아닌 요소라고 가정, 2를 곱했을 때 최대값보다 크다면 -1 반환 
        if num != maxValue and maxValue < num * 2:
            return -1
    return maxIndex

'자료구조 & 알고리즘 > Leetcode' 카테고리의 다른 글

19. Spiral Matrix  (1) 2022.09.22
17. Plus One  (0) 2022.09.16
15. Find Pivot Index(1991)  (0) 2022.09.13
14. Find All Numbers Disappeared in an Array  (0) 2022.06.05
13. Third Maximum Number  (0) 2022.06.04