알고리즘 풀이 방법입니다.
문제(Problem) -> 생각(Think) -> 해결책(Solution) -> 리뷰(Review) 를 통해서 정리해서 작성합니다.
Problem📄

https://school.programmers.co.kr/learn/courses/30/lessons/176963

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr


Think🤔

HashMap을 이용해서 key 값과 같으면 그 value 값 삽입


Solution✍
import java.util.HashMap;

class Solution {
    public int[] solution(String[] name, int[] yearning, String[][] photo) {
        HashMap<String, Integer> hm = new HashMap();
        int[] answer = new int[photo.length];
        int sum = 0;
        
        for(int i=0; i<name.length; i++){
            hm.put(name[i],yearning[i]);
        }
        
        for(int i=0; i<photo.length; i++){
            for(int j=0; j<photo[i].length; j++){
                String key = photo[i][j];
                if(hm.containsKey(key)){
                    answer[i] += hm.get(key);
                }
            }
        }
        
        
        return answer;
    }
}

// HASH MAP 사용 
// 1. HashMap key에 name[0] value에 yearning[0]
// int sum = 0; 이용 
// for문 photo 돌림

Review🤩

다른 사람들 풀이를 보니 , IntStream으로 푸신분이 많았다.

 

IntStream은 Java 8에서 추가된 클래스

정수요소를 처리할때 특화되어 있음 

병렬처리를 지원해서 효율성에 좋음

 

import java.util.List;
import java.util.stream.IntStream;

public class IntStreamExample {
    public static void main(String[] args) {
        List<Integer> numbers = List.of(1, 2, 3, 4, 5);
        int sum = numbers.stream().mapToInt(Integer::intValue).sum();
        System.out.println("Sum: " + sum);
    }
}

stream 패키지를 사용하며 , 문법은 이와 같다.

 

스트림 생성 방법

List<String> list = Arrays.asList("apple", "banana", "cherry");
Stream<String> stream = list.stream();

String[] array = {"apple", "banana", "cherry"};
Stream<String> stream = Arrays.stream(array);

Stream<String> stream = Stream.of("apple", "banana", "cherry");

list , 배열 , 스트림메서드를 이용해서 스트림 생성할 수 있다.

 

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class StreamExample {
    public static void main(String[] args) {
        List<String> fruits = Arrays.asList("apple", "banana", "cherry", "date", "elderberry");

        // 스트림 생성
        Stream<String> fruitStream = fruits.stream();

        // 중간 연산: 길이가 5 이상인 과일 필터링
        Stream<String> filteredStream = fruitStream.filter(fruit -> fruit.length() >= 5);

        // 최종 연산: 필터링된 과일을 리스트로 수집
        List<String> filteredFruits = filteredStream.collect(Collectors.toList());

        // 결과 출력
        System.out.println(filteredFruits); // ["banana", "cherry", "elderberry"]
    }
}

stream() 구문으로 스트림생성

filter를 이용해서 조건에 맞는 요소 선택 가능

가독성 있게 추출할 수 있다.


 

+ Recent posts