본문 바로가기

Algorithm/자료구조

(C++) - LeetCode (easy) 575. Distribute Candies

반응형

https://leetcode.com/problems/distribute-candies/description/

 

Distribute Candies - LeetCode

Can you solve this real interview question? Distribute Candies - Alice has n candies, where the ith candy is of type candyType[i]. Alice noticed that she started to gain weight, so she visited a doctor. The doctor advised Alice to only eat n / 2 of the can

leetcode.com

자료구조 map을 이요해 해결한 문제였습니다.

📕 풀이방법

📔 입력 및 초기화

1. 먹을 수 있는 사탕은 n/2개이므로 이를 변수 limit를 선언해 저장해줍니다.2. 정답 변수 ans를 선언해 줍니다.3. 사탕의 종류 하나인 여러 사탕을 가질 수 있으므로 사탕의 종류가 몇 개인지 확인하기 위해 candyMapPerType을 선언 후 key에는 type, value에는 사탕 개수를 저장해줍니다.

📔 풀이과정

candyMapPerType에 대해 for loop를 수행해 limit를 넘지 않는 한 ans를 증가시켜 먹을 수 있는 최대 type개수를 구합니다.

📔 정답 출력 | 반환

ans를 반환합니다.


📕 Code

📔 C++

class Solution {
public:
    int distributeCandies(vector<int>& candyType) {
        int limit = candyType.size() / 2;
        int ans = 0;
        map <int, int> candyMapPerType;
        for(auto c : candyType) {
            candyMapPerType[c]++;
        }
        for(auto c : candyMapPerType) {
            if(ans == limit) break;
            ans++;
        }
        return ans;
    }
};

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.