1.문제
Majority Element - LeetCode
Can you solve this real interview question? Majority Element - Given an array nums of size n, return the majority element. The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists
leetcode.com
2.문제설명

이 문제는 빈도수를 체크 하는 문제이지만 대신 조건이 하나 있다. 현제 배열의 길이의 절반 이상의 빈도수를 가지고 있는 것을 반환하는 조건이다.
3.소스코드
class Solution {
public int majorityElement(int[] nums) {
int majorityNum = nums.length / 2;
Map<Integer,Integer> countMap = new HashMap<>();
for(int i : nums){
countMap.put(i,countMap.getOrDefault(i,0)+1);
if(countMap.get(i) > majorityNum){
return i;
}
}
return 0;
}
}
4. 문제 해설
코딩 테스트를 파이썬으로 만하다 자바로 하려니 뚜닥거리는...헷갈리는 그런게 있지만 기억을 되세겨 풀었다.
문제에서 주어진 조건 부터 주어진 배열에 길이의 절반 이상 을 가진 요소를 찾아야 하므로 길이 / 2 를 한다.
빈도수를 체크하기 위해 Map 구조로 추가하며 빈도수를 올려간다.
반복문을 통해 요소를 Map에 집어 넣어주는데 Map.getOrDefault() 메서드를 활용해 준다.
이 메서드는 만약 해당 키가 존재한다면 0으로 default 를 하고 +1 을 통해 빈도수를 증가 시키는 역할을 해준다
다음 조건문을 통해 그 배열의 길이 절반 이상인지 체크 후 reutrn for 문을 빠져나와도 없으면 0
'Algorithm' 카테고리의 다른 글
| [leetCode 121] Best Time to Buy and Sell Stock (Java) (0) | 2023.08.24 |
|---|---|
| [leetCode 189번] Rotate Array (Java) (0) | 2023.08.24 |
| [leetCode 80번] Remove Duplicates from Sorted Array II (Java) (0) | 2023.08.24 |
| [leetCode 26번] Remove Duplicates from Sorted Array (Java) (0) | 2023.08.24 |
| [leetCode 27번] Remove Element (JAVA) (0) | 2023.08.24 |