본문 바로가기
Coding test/Programmers

[프로그래머스][JAVA] 같은 숫자는 싫어

by jepa 2023. 8. 9.
728x90
SMALL

https://school.programmers.co.kr/learn/courses/30/lessons/12906

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

해당 문제는 LinkedList를 이용하여 풀었다.

 

풀이를 그림으로 그리면 아래와 같다.

2번에서 peekLast가 삽입할 숫자와 다르면 넣는다.

 

이를 반복하면 list에는 연속해서 같은 숫자가 들어갈 일은 없다.

import java.util.*;

public class Solution {
    public int[] solution(int []arr) {
        ArrayList<Integer> tempList = new ArrayList<Integer>();
        int preNum = 10;
        for(int num : arr) {
            if(preNum != num)
                tempList.add(num);
            preNum = num;
        }       
        int[] answer = new int[tempList.size()];
        for(int i=0; i<answer.length; i++) {
            answer[i] = tempList.get(i).intValue();
        }
        return answer;
    }
}
728x90
LIST