[프로그래머스] 같은 숫자는 싫어
2020. 6. 19. 18:37ㆍ프로그래머스/LEVEL 1
import java.util.*;
public class Solution {
public int[] solution(int []arr) {
int[] answer = {};
List<Integer> answerList = new ArrayList<>();
answerList.add(arr[0]);
for(int i=1; i<arr.length; i++){
if(arr[i]!=arr[i-1]){
answerList.add(arr[i]);
}
}
answer = new int[answerList.size()];
for(int i=0; i<answer.length; i++){
answer[i] = answerList.get(i);
}
return answer;
}
}
1. 첫번째 숫자는 무조건 들어가야하므로 answerList에 넣는다.
2. 두번째 인덱스 부터 끝까지 돌면서 이 전의 숫자와 다르다면 answerList에 추가하고, 같다면 추가하지 않는다.
3. answerList에는 전의 숫자와 다른 숫자들만 들어가므로 이것을 answer배열에 옮겨주면 된다.
'프로그래머스 > LEVEL 1' 카테고리의 다른 글
[프로그래머스] 문자열 내림차순으로 배치하기 (0) | 2020.06.19 |
---|---|
[프로그래머스] 2016년 (0) | 2020.06.19 |
[프로그래머스] 시저 암호 (0) | 2020.06.19 |
[프로그래머스] K번째수 (0) | 2020.06.19 |
[프로그래머스] 문자열 내 p와 y의개수 (0) | 2020.06.19 |