
뭔가 큐를 사용해야되는 건줄 알았는데
import java.util.*;
public class Solution {
public int[] solution(int []arr) {
List<Integer> list = new ArrayList<>();
Queue<Integer> q = new LinkedList<>();
for(int n : arr) {
q.offer(n);
}
int temp = q.poll();
list.add(temp);
while(!q.isEmpty()) {
int now = q.poll();
if (now != temp) {
list.add(now);
}
temp = now;
}
return list.stream().mapToInt(i->i).toArray();
}
}

일단 실패
스택 사용
import java.util.*;
public class Solution {
public int[] solution(int []arr) {
Stack<Integer> stack = new Stack<>();
for(int i=0; i<arr.length; i++) {
if (i == 0)
stack.push(arr[i]);
else if (stack.peek() != arr[i])
stack.push(arr[i]);
}
return stack.stream().mapToInt(i->i).toArray();
}
}

스택 + stream보다 for문으로 배열에 넣는게 더 빠르군 ...
import java.util.*;
public class Solution {
public int[] solution(int []arr) {
Stack<Integer> stack = new Stack<>();
for(int i=0; i<arr.length; i++) {
if (i == 0)
stack.push(arr[i]);
else if (stack.peek() != arr[i])
stack.push(arr[i]);
}
int[] answer = new int[stack.size()];
for(int i=stack.size()-1; i>=0; i--) {
answer[i] = stack.pop();
}
return answer;
}
}

그냥 list 사용
import java.util.*;
public class Solution {
public int[] solution(int []arr) {
List<Integer> list = new ArrayList<>();
list.add(arr[0]);
int temp = list.get(0);
for(int i=1; i<arr.length; i++) {
if (arr[i] != temp)
list.add(arr[i]);
temp = arr[i];
}
return list.stream().mapToInt(i->i).toArray();
}
}

'코딩테스트 > Programmers' 카테고리의 다른 글
| [Programmers] 이상한 문자 만들기 (0) | 2023.08.26 |
|---|---|
| [Programmers] 3진법 뒤집기 (0) | 2023.08.25 |
| [Programmers] 약수의 개수와 덧셈 (0) | 2023.08.14 |
| [Programmers] 제일 작은 수 제거하기 (0) | 2023.08.10 |
| [Programmers] 서울에서 김서방 찾기 (속도 줄이기) (0) | 2023.08.03 |