알고리즘/프로그래머스

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

K.두부 2022. 9. 1. 22:51
반응형

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

 

프로그래머스

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

programmers.co.kr

풀이

이번 문제는 배열로 푸는 게 훨씬 쉽다고 생각했다. 하지만 문제가 스택/큐로 분류가 되어있으니까 스택을 이용해서 풀어보려고한다.

 

preNum이라는 변수에 배열 arr에 들어갈 수 없는 임의의 숫자를 넣어준 후에 인접한 숫자가 같은 수가 아니면 queue에 넣어주면 끝이다.

import java.util.*;
public class Solution {
public int[] solution(int []arr) {
// [실행] 버튼을 누르면 출력 값을 볼 수 있습니다.
System.out.println("Hello Java");
Queue<Integer> que = new LinkedList<>();
// 인접한 인자가 다른 수면 queue에 add
int preNum = 10;
for (int num : arr) {
if (preNum != num) {
que.add(num);
}
preNum = num;
}
int[] answer = new int[que.size()];
for (int i=0; i<answer.length; i++) {
answer[i] = que.poll();
}
return answer;
}
}

 

<ArrayList로 푸는 방법>

import java.util.*;
public class Solution {
public int[] solution(int []arr) {
// [실행] 버튼을 누르면 출력 값을 볼 수 있습니다.
System.out.println("Hello Java");
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);
}
return answer;
}
}

반응형