-
[LeetCode] 747. Largest Number At Least Twice of OthersLeetCode 2021. 11. 24. 22:41728x90
https://leetcode.com/problems/largest-number-at-least-twice-of-others/
Largest Number At Least Twice of Others - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
Largest Number At Least Twice of Others - Easy

배열 내의 최대값이 다른 모든 수의 2배 이상이라면 최대값의 index를, 아니라면 -1을 리턴하는 문제다.
다른 모든 수를 생각할 필요 없이, 가장 큰 수와 두번째로 큰 수만 비교해주면 된다.
따라서 priority queue를 써줘도 좋다.
내 풀이는 아래와 같다.
최대값 M을 -1, ret을 -1로 초기화해주고, 배열을 훑으며
해당값이 M보다 크다면 ret을 새로 설정해주는데,
이 때, 해당값이 2*M 보다 크다면 ret을 해당 index로, 아니라면 -1로 설정해준다.
그리고 M은 해당값으로 설정해준다.
해당값이 M보다 작고 해당값*2가 M보다 크다면 ret을 -1로 설정해준다.
전체 풀이 코드
class Solution { public: int dominantIndex(vector<int>& nums) { int M = -1, ret = -1; for (int i=0; i<nums.size(); i++) { if (M<nums[i]) { ret = 2*M<=nums[i]?i:-1; M = nums[i]; } else if (M<2*nums[i]) ret = -1; } return ret; } };'LeetCode' 카테고리의 다른 글
[LeetCode] 35. Search Insert Position (0) 2021.11.26 [LeetCode] 53. Maximum Subarray (0) 2021.11.25 [LeetCode] 986. Interval List Intersections (0) 2021.11.24 [LeetCode] 952. Largest Component Size by Common Factor (0) 2021.11.23 [LeetCode] 540. Single Element in a Sorted Array (0) 2021.11.20