[프로그래머스] 빈 배열에 추가, 삭제하기

최혜원·2023년 6월 13일
2

Algorithm

목록 보기
2/3

📍문제설명

아무 원소도 들어있지 않은 빈 배열 X가 있습니다.
길이가 같은 정수 배열 arrboolean 배열 flag가 매개변수로 주어질 때,
flag를 차례대로 순회하며 flag[i]가 true라면 X의 뒤에 arr[i]arr[i] × 2 번 추가하고,
flag[i]가 false라면 X에서 마지막 arr[i]개의 원소를 제거한 뒤 X를 return 하는 solution 함수를 작성해 주세요.


📍나의풀이

import java.util.ArrayList;
import java.util.Arrays;

class Solution2 {

    public int[] solution(int[] arr, boolean[] flag) {

        ArrayList<Integer> list = new ArrayList<>();

        for (int i = 0; i < arr.length; i++) {
            if (flag[i]) {
                for (int j = 0; j < arr[i] * 2; j++) {
                    list.add(arr[i]);
                }
            } else {
                for (int j = 0; j < arr[i]; j++) {
                    // 0부터니까 -1
                    list.remove(list.size() - 1);
                }
            }
        }

        int[] answer = new int[list.size()];

        for (int i = 0; i < list.size(); i++) {
            answer[i] = list.get(i);
        }

        return answer;
    }
    public static void main(String[] args) {
        Solution2 solution2 = new Solution2();
        System.out.println(Arrays.toString(solution2.solution(new int[]{3, 2, 4, 1, 3}, new boolean[]{true, false, true, false, false})));
    }
}

profile
어제보다 나은 오늘

0개의 댓글