문제
프로그래머스 [같은 숫자는 싫어]
문제 링크: https://school.programmers.co.kr/learn/courses/30/lessons/12906
해결 방법
- 비교를 위한 초기값과 임시 list를 ArrayList로 생성
- arr배열의 요소를 for문을 돌면서 현재 값이 previous와 다를 때만 리스트에 추가
- previous는 새로운 값이 추가될 때마다 업데이트
- list에 있는 값을 int[] 배열로 변환
코드
import java.util.*;
public class Solution {
public int[] solution(int[] arr) {
List<Integer> list = new ArrayList<>();
int previous = -1; // 초기값으로 배열에 포함되지 않은 값 설정
for (int num : arr) {
if (num != previous) { // 이전 값과 다른 경우에만 추가
list.add(num);
previous = num;
}
}
// ArrayList를 int[] 배열로 변환하여 반환
int[] answer = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
answer[i] = list.get(i);
}
return answer;
}
}
- 참고할 다른 풀이 방법
더보기
- stack 사용
import java.util.*;
public class Solution {
public Stack<Integer> solution(int []arr) {
Stack<Integer> stack = new Stack<>();
for(int num : arr){
if(stack.size() == 0 || stack.peek() != num){
stack.push(num);
}
}
return stack;
}
}
import java.util.*;
public class Solution {
public int[] solution(int []arr) {
List<Integer> list = new ArrayList<Integer>();
list.add(arr[0]);
for (int i = 1; i < arr.length; i++) {
if (arr[i] != arr[i - 1])
list.add(arr[i]);
}
int[] answer = new int[list.size()];
for (int i = 0; i < list.size(); i++)
answer[i] = list.get(i);
return answer;
}
}
import java.util.*;
public class Solution {
public int[] solution(int []arr) {
StringBuilder sb = new StringBuilder();
int size = arr.length;
sb.append(arr[0]);
for(int i=1; i<size; i++){
if(arr[i-1]!=arr[i]) sb.append(arr[i]);
}
String[] array = sb.toString().split("");
size = array.length;
int[] answer = new int[size];
for(int i=0; i<size; i++){
answer[i] = Integer.parseInt(array[i]);
}
return answer;
}
}
import java.util.*;
public class Solution {
public int[] solution(int []arr) {
LinkedList<Integer> list = new LinkedList<Integer>();
list.add(arr[0]);
for(int i=1; i<arr.length;i++){
if(arr[i]!=list.getLast()){
list.add(arr[i]);
}
}
Integer[] listing = list.toArray(new Integer[list.size()]);
int []answer =Arrays.stream(listing).mapToInt(Integer::intValue).toArray();
return answer;
}
}
'개발 공부 > 코딩테스트' 카테고리의 다른 글
99클럽 코테 스터디 17일차 TIL - 스택/큐 (1) | 2024.11.14 |
---|---|
99클럽 코테 스터디 16일차 TIL - 스택/큐 (1) | 2024.11.12 |
99클럽 코테 스터디 12일차 TIL - 스택 (0) | 2024.11.08 |
99클럽 코테 스터디 11일차 TIL - 해시 (1) | 2024.11.08 |
99클럽 코테 스터디 10일차 TIL - 해시 (1) | 2024.11.06 |