White Cat's Paw

알고리즘

[프로그래머스] 배열의 원소 삭제하기

JungMayo 2025. 4. 11. 13:51

정수 배열 arr delete_list가 있습니다. arr의 원소 중 delete_list의 원소를 모두 삭제하고 남은 원소들은 기존의 arr에 있던 순서를 유지한 배열을 return 하는 solution 함수를 작성해 주세요.

 

1. contains로 delete_list의 원소를 포함하는지 확인하기 위해 arr를 Set으로 설정

2. 배열길이를 알 수 없어서 새로운 List를 만들고 delete_list가 빠진 arr List를 생성할 예정

3. arr List를 stream.mapToInt,toArray()를 사용하여 int 배열로 만들어서 return한다.

 

import java.util.*;

class Solution {
    public int[] solution(int[] arr, int[] delete_list) {
        Set<Integer> set = new HashSet<>();
        for(int a : delete_list){
            set.add(a);
        }
        List<Integer> list = new ArrayList<>();
        for(int b : arr){
            if(!set.contains(b)){
                list.add(b);
            }
        }

        return list.stream().mapToInt(i->i).toArray();
    }
}