반응형
https://leetcode.com/problems/largest-number-at-least-twice-of-others/description/
Largest Number At Least Twice of Others - LeetCode
Can you solve this real interview question? Largest Number At Least Twice of Others - 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 numbe
leetcode.com
간단 구현 문제였습니다.
📕 풀이방법
📔 입력 및 초기화
가장 큰 수를 저장할 변수 maxNum과 해당 index를 저장할 maxIdx를 선언 후 0으로 초기화 해줍니다.
📔 풀이과정
nums의 원소를 순회하며 maxNum보다 큰 수가 있다면 해당 값과 index를 맞는 변수에 저장합니다.
📔 정답 출력 | 반환
nums의 원소를 순회하며 해당 원소의 2배에 해당하는 값이 maxNum보다 크다면 -1을 아니라면 maxIdx를 반환해줍니다.
📕 Code
📔 C++
class Solution {
public:
int dominantIndex(vector<int>& nums) {
int maxNum = 0;
int maxIdx = 0;
for(int i = 0; i < nums.size(); i++) {
if(maxNum < nums[i]) maxNum = nums[i], maxIdx = i;
}
for(int i = 0; i < nums.size(); i++) {
if(i == maxIdx) continue;
if(nums[i] * 2 > maxNum) return -1;
}
return maxIdx;
}
};
*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.
'Algorithm > Implementation' 카테고리의 다른 글
(C++) - LeetCode (easy) 762. Prime Number of Set Bits in Binary Representation (0) | 2023.07.10 |
---|---|
(C++) - LeetCode (easy) 748. Shortest Completing Word (0) | 2023.07.07 |
(C++) - LeetCode (easy) 728. Self Dividing Numbers.cpp (0) | 2023.06.26 |
(C++) - LeetCode (easy) 709. To Lower Case (0) | 2023.06.21 |
(C++) - LeetCode (easy) 693. Binary Number with Alternating Bits (0) | 2023.06.13 |