본문 바로가기

Algorithm/자료구조

(C++) - LeetCode (easy) 1287. Element Appearing More Than 25% In Sorted Array

반응형

https://leetcode.com/problems/element-appearing-more-than-25-in-sorted-array/description/

 

Element Appearing More Than 25% In Sorted Array - LeetCode

Can you solve this real interview question? Element Appearing More Than 25% In Sorted Array - Given an integer array sorted in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time, return that integer.   Ex

leetcode.com

map 활용 문제였습니다.

📕 풀이방법

📔 입력 및 초기화

first는 숫자, second는 빈도 수를 저장하는 freqMap을 선언해 줍니다.

📔 풀이과정

1. arr에 대해 loop를 수행하면서 freqMap에 빈도수를 저장해줍니다.

2. freqMap에 대해 loop를 수행하며 빈도수 * 4 > arr size인 f.first를 찾아 반환해줍니다.


📕 Code

📔 C++

class Solution {
public:
    int findSpecialInteger(vector<int>& arr) {
        map <int,int> freqMap;
        for(auto a : arr) {
            freqMap[a]++;
        }
        for(auto f : freqMap){
            if(f.second * 4 > arr.size()) return f.first;
        }
        return 0;
    }
};

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