바로 전 값을 담아 둘tempNum
이라는 변수를 선언해주고 문제에서 주어진 원소의 조건인 0~9 범위 밖의 값을 넣어둔다. 범위 안의 값이면 문제에서 요구하는 조건 (연속적으로 나타나는 숫자 제거)을 위한 비교가 불가능하기 때문이다.
if문과는 상관없이 tempNum에 num을 넣어준다. 반복문을 돌 때 tempNum에는 이전의 숫자가 들어있기 때문에 tempNum != num
인 경우에만 tempList에 저장해준다.
tempNum = num
이므로 tempList에 저장되지 않고 tempNum에는 1을 넣는다. import java.util.*;
public class Solution {
public int[] solution(int []arr) {
ArrayList<Integer> tempList = new ArrayList<Integer>();
int tempNum = 10;
for(int num : arr) {
if(tempNum != num) {
tempList.add(num);
}
tempNum = num;
}
int[] answer = new int[tempList.size()];
for(int i = 0; i < answer.length; i++) {
answer[i] = tempList.get(i);
}
return answer;
}
}
tempList.get(i)
는 해당 인덱스의 Integer 객체를 return한다. int형으로 변환하기 위해서는 intValue()
를 해줘야 하지만 JDK 1.5부터는 자바 컴파일러가 오토 박싱과 언박싱 처리를 해주기 때문에 자동으로 변환된다.