본문 바로가기

Algorithm/Programmers

Level 1: 같은 숫자는 싫어, 배열의 연속된 중복 Element 제거

이 문서의 내용

    문제 풀이: Stream 필터 사용

    배열을 Stream으로 필터합니다. 필터는 이전 Element의 값과 일치하는지(Element의 연속성)에 대한 검사입니다.

    이전 Element에 대한 연속성을 검증하려면 이전 Element 값을 저장하고 참조 할 수 있어야 합니다.

    import java.util.*;
    
    public class Solution {
    	public static class WrappedInt {
    		public Integer v = null;
    	}
    	
    	public int[] solution(int []arr) {
    		WrappedInt prev = new WrappedInt();
    		return Arrays.stream(arr).boxed().filter(i -> {
    			if (null == prev.v) {
    				prev.v = i;
    				return true;
    			}
    			else if (i == prev.v) {
    				return false;
    			}
    			else {
    				prev.v = i;
    				return true;
    			}
    		}).mapToInt(Integer::intValue).toArray();
    	}
    }
    코드 비고
    Line 9 WrappedInt 람다 표현식에서 상태 저장을 위한 Object를 정의하고 엑세스합니다.
    Line 10 Arrays.stream().boxed().filter() 배열을 Stream으로 filter합니다.
    Line 22 mapToInt(Integer::intValue).toArray() 필터 후 Stream<Integer> 타입을 int[] 타입으로 캐스팅합니다.

    문제 풀이: 단순 Iterating으로 검사

    Stream을 사용하지 않고 단순히 입력된 배열을 순회하면서 처리합니다.

    import java.util.*;
    
    public class Solution {
    	public int[] solution(int []arr) {
    		List<Integer> o = new ArrayList<>();
    		Integer prev = null;
    		for (int el : arr) {
    			if (null == prev || prev != el) {
    				o.add(el);
    			}
    			
    			prev = el;
    		}
    		
    		return o.stream().mapToInt(Integer::intValue).toArray();
    	}
    }
    코드 비고
    Line 6 Integer prev 직전 Element에 대한 값을 저장합니다.
    Line 15 stream().mapToInt(Integer::intValue).toArray() List<Integer> 타입을 int[] 타입으로 캐스팅합니다.