가랑비에 옷 젖는 줄 모른다 💻/🌰코테문풀_꾸준히

[0단계/8점] 무작위로 K개의 수 뽑기

잔뜩 2025. 2. 4. 00:49

 

LinkedHashSet 은 중복제거 그리고 순서도 유지해줌! HashSet은 중복제거는 되는데 순서 유지가 안됌 

import java.util.*;

class Solution {
    public int[] solution(int[] arr, int k) {
        Set<Integer> resultList = new LinkedHashSet<>();
        
        // 중복 제거하며 최대 k개까지 수집
        for (int i = 0; i < arr.length; i++) {
            resultList.add(arr[i]);
            if (resultList.size() == k) {
                break;
            }
        }

        // k개의 요소를 확보한 경우 바로 반환
        if (resultList.size() == k) {
            return resultList.stream().mapToInt(Integer::intValue).toArray();
        } 

        // k보다 부족한 경우, -1을 추가
        List<Integer> newResultList = new ArrayList<>(resultList);
        while (newResultList.size() < k) {
            newResultList.add(-1);
        }

        return newResultList.stream().mapToInt(Integer::intValue).toArray();
    }
}
728x90