-
프로그래머스 - 같은 숫자는 싫어 [자바]Algorithms/- 프로그래머스 2022. 2. 2. 11:28
- 문제 링크 : 같은 숫자는 싫어
정답
import java.util.*; import java.util.stream.*; public class Solution { public int[] solution(int []arr) { List<Integer> list = new ArrayList<>(); int a = -1; for(int n : arr){ if(a != n){ list.add(n); a = n; } } return list.stream().mapToInt(Integer::intValue).toArray(); } }
분석
- 중복제거 문제
// 굳이 a == -1 초기 값일때 if문으로 분기 처리할 이유가 없음. for(int n : arr){ if(a == -1){ list.add(n); a = n; }else{ if(a != n){ list.add(n); a = n; } } } //아래와 같이 변경 for(int n : arr){ if(a != n){ list.add(n); a = n; } }
반응형