[leetcode] Easy-169번. Majority Element 문제풀이

반응형
728x90
반응형

문제

https://leetcode.com/problems/majority-element/

 

Majority Element - 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

 

 

 

풀이코드

package SITE03_leetcode.easy;

import SITE03_leetcode.medium.M004_leetCode4_median_of_two_sorted_arrays;

import java.util.*;
import java.util.stream.Collectors;

/**
 * https://leetcode.com/problems/majority-element/
 */
public class E001_leetCode165_Majority_element {
    public static void main(String[] args) {
        E001_leetCode165_Majority_element solution = new E001_leetCode165_Majority_element();

        int[] a = new int[]{3, 2, 3};

        System.out.println(solution.majorityElement(a));
    }

    public int majorityElement(int[] nums) {
        int target = nums.length / 2;

        Map<Integer, Integer> map = new HashMap<>();
        for (int key : nums) {
            if (map.containsKey(key)) {
                map.put(key, map.get(key) + 1);
            } else {
                map.put(key, 1);
            }
        }

        Set<Integer> set = map.entrySet().stream()
                // key 에 해당하는 value 중 target 보다 큰 것으로 필터링
                .filter(key -> key.getValue() > target)
                // 필터링 된 Entry 의 key 추출
                .map(Map.Entry::getKey)
                // Set 으로 변경 (중복제거)
                .collect(Collectors.toSet());

        // 최대값 추출 
        return set.stream().max(Integer::compareTo).get();
    }
}

 

Map 에 담고, 스트림을 활용하여 풀이해보았다.

 

 

 

 

 

반응형

Designed by JB FACTORY