본문 바로가기

프로그래머스/lv1

같은 숫자는 싫어

/* 같은 숫자는 싫어
 * 배열 arr가 주어집니다.
 * 배열 arr의 각 원소는 숫자 0부터 9까지로 이루어져 있습니다.
 * 이때, 배열 arr에서 연속적으로 나타나는 숫자는 하나만 남기고
 * 전부 제거하려고 합니다.
 * 단,제거된 후 남은 수들을 반환할 때는 배열 arr의 원소들의 순서를 유지해야 합니다.
 *
 * 배열 arr의 크기 : 1,000,000 이하의 자연수
 * 배열 arr의 원소의 크기 : 0보다 크거나 같고 9보다 작거나 같은 정수
 *
 * arr              answer
 * [1,1,3,3,0,1,1]  [1,3,0,1]
 * [4,4,4,3,3]      [4,3]
 */
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import java.util.*;
public class Programmer_1_37 {
    static int[] a1 = {1,1,3,3,0,1,1};
    static int[] a2 = {4,4,4,3,3};
    public Stack<Integer> solution(int []arr) {
        int[] answer = {};
        Stack<Integer> st = new Stack<Integer>();
        for(int i = 0; i < arr.length; i++){
            if(st.empty())  st.push(arr[i]);
            else{
                if(st.peek() != arr[i]) st.push(arr[i]);
            }
        }
        System.out.println(st);
        
        return st;
    }
    public static void main(String args[]){
        Programmer_1_37 t = new Programmer_1_37();
        System.out.println("---------------------------------------");
        System.out.println("result = " + t.solution(a1));
        System.out.println("---------------------------------------");
        // System.out.println("result = " + t.solution(a2));
        System.out.println("---------------------------------------");
    }
}
 
cs

'프로그래머스 > lv1' 카테고리의 다른 글

3진법 뒤집기  (1) 2022.12.20
이상한 문자 만들기  (0) 2022.12.20
최대공약수와 최소공배수  (0) 2022.12.20
직사각형 별찍기  (0) 2022.12.19
행렬의 덧셈  (0) 2022.12.19