99클럽 코테 스터디 2일차 TIL + 오늘의 학습 키워드

angie·2024년 5월 21일

TIL

목록 보기
2/6

오늘의 학습 키워드

  • 해시

해결 방법

문제: 의상

  • 해시맵에 <옷 종류, 옷 개수> 를 저장한 후, 해시맵을 순회하면서 확률을 계산한다. +1을 하는 이유는 옷을 입지 않는 경우를 포함시키기 때문이다. 그 후 아무것도 입지 않는 경우를 제외하기 위해 -1을 한다.
import java.util.*;

class Solution {
    public int solution(String[][] clothes) {        
        HashMap<String, Integer> h1 = new HashMap<>();
        
        for(int i = 0; i < clothes.length; i++){   
            String key = clothes[i][1];                  
            if(h1.containsKey(key)){            
                h1.replace(key, h1.get(key)+1);
            }else{
                h1.put(key, 1);            
            }
        }
        
        int sum = 1;
        
        for (Map.Entry<String, Integer> entry : h1.entrySet()) {
            sum = sum * (entry.getValue()+1);
        }
        
        return sum-1;
    }
}

무엇을 새롭게 알았는지

HashMap

HashMap이란?
키(Key)와 밸류(Value)가 짝을 이루어 데이터를 저장한다. 데이터의 저장위치를 해시함수를 통해 바로 알 수 있기 때문에 데이터의 추가, 삭제, 특히 검색이 빠르다는 장점이 있다.

생성방법

  • HashMap<String, String> h1 = new HashMap<String, String>( );

데이터 추가

  • put(K key, V value)

데이터 확인

  • boolean containsKey(Object key)
    : key와 일치하는 데이터가 있는지 여부를 반환합니다. (있으면 true)
  • boolean containsValue(Object value)
    : value가 일치하는 데이터가 있는지 여부를 반환합니다. (있으면 true)
  • boolean isEmpty( )
    : 데이터가 빈 상태인지 여부를 반환합니다. (빈 상태면 true)
  • int size( )
    : key-value 맵핑 데이터의 개수를 반환합니다. 

데이터 반환

  • get(Object key)
    : key와 맵핑된 value값을 반환합니다. 

HashMap 반복

  • entrySet() 사용하기
	Set<Entry<Integer, String>> entrySet = map.entrySet();

	for (Entry<Integer, String> entry : map.entrySet()) {
   		 System.out.println("key : " + entry.getKey() + " / value:" + 		entry.getValue());
	}
  • Iterator 사용하기
    Iterator는 자바의 Collections Framework에서 컬렉션에 저장되어 있는 요소들을 읽어오는 방법을 표준화한 것이다.
    • hasNext(): 읽어올 요소가 있으면 true, 없으면 false 리턴
    • next(): 다음 데이터를 리턴
    • remove(): next()로 리턴받은 요소를 삭제
	Iterator<Entry<Integer, String>> it = map.entrySet().iterator();

	while(it.hasNext()) {
		Entry<Integer, String> entry = it.next();
		System.out.print("key-value : "+entry+" / ");
		System.out.println("key : "+entry.getKey()+" / value : "+entry.getValue());
	}
profile
열심히 달리는 개발자

0개의 댓글