카테고리 없음

99클럽 코테 스터디 TIL 3일차

느리지만 꾸준하게 2024. 5. 22. 17:06
  • 오늘의 학습 키워드 : stack, Stream API map 메서드
  1. stack -> LIFO(Last In First Out) 구조로 마지막에 들어간 값이 제일 처음 출력되는 방식
  2. 후입선출이라고도 하고 단방향 입출력 구조로서 깊이우선탐색(DFS)에서도 쓰인다.
  3. 재귀 함수의 동작 흐름과 같은 구조를 가짐

stack 메서드

  1. push() - 값을 스택에 추가

 

  1. peek() - 스택의 마지막 요소 반환(스택이 비어있는데 peek() 메서드 호출 하면 NoSuchElementException 예외 터짐)

 

  1. pop() - 스택의 마지막 요소 제거하고 해당 값 반환

 

  1. empty() - 스택이 비어있는지 여부 판단 - 비어있으면 true, 아니면 false를 반환

 

  1. search() - 메서드의 인자를 스택에서 검색하고 해당 위치 반환(값이 빠져나오는 순서를 말함), 찾는 값이 없으면 -1을 반환
class 	StackEx {

	public static void main(String[] args) {
    	Stack<Integer> stackInt = new Stack<>();
        
        stackInt.push(100);
		stackInt.push(200);
		stackInt.push(300);
		stackInt.push(400);
        
        
        // [100, 200, 300, 400]
        
        System.out.println(stackInt.search(200));
        System.out.println(stackInt.search(400));
        System.out.println(stackInt.search(500));
    
    
    }

}

// 출력
3
1
-1

 

 

 

Stream API map 메서드

- map이 뭘까? map은 Stream의 요소들을 내가 사용할 형태로 바꾸거나, 사용할 요소를 뽑아내는 것이라고 생각된다.

 

아래는 공식문서의 map 메소드 설명

Returns a stream consisting of the results of applying the given function to the elements of this stream.

 

map과 관련된 메소드(블로그 참고)

1. maptoInt

2. mapToObj

3. flatMap

 

 

 

 

프로그래머스 - 같은 숫자는 싫어

- ArrayList로 구현

import java.util.*;

public class Solution {
    public int[] solution(int []arr) {
        ArrayList<Integer> answerList = new ArrayList<Integer>();
        
        int value = -1;
        for(int i = 0; i < arr.length; i++) {
            if (arr[i] != value) {
                answerList.add(arr[i]);
                value = arr[i];
            }
        }
        return answerList.stream().mapToInt(i -> i).toArray();
    }
}

 

 

- stack로 구현

import java.util.*;

public class Solution {
    public int[] solution(int []arr) {
        int[] answer;
        
        // integer를 담는 Stack 선언
        Stack<Integer> st = new Stack<Integer>();
        
        // 전달받은 배열만큼 반복문을 돌면서
        for(int i = 0; i < arr.length; i++) {
            if (i == 0) st.push(arr[i]);
            
            else if(st.peek() != arr[i]) st.push(arr[i]);
        }
        
        answer = new int[st.size()];
        
        for(int i = st.size() - 1; i >= 0; i--){
            answer[i] = st.pop();
        }
        
        System.out.println("Hello Java");
        
        return answer;
    }
}