코딩테스트/Programmers

[Programmers] 같은 숫자는 싫어 - 여러 방법

주니어주니 2023. 8. 25. 18:02

 

 

 

뭔가 큐를 사용해야되는 건줄 알았는데

 

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();
    }
}