보라코딩
프로그래머스 자바 :: Hash 본문
HashMap 관련 공부
import java.util.HashMap;
public class HashExample {
public static void main(String[] args) {
// HashMap 생성
HashMap<String, Integer> hashMap = new HashMap<>();
// 데이터 추가
hashMap.put("apple", 1);
hashMap.put("banana", 2);
hashMap.put("cherry", 3);
// 데이터 조회
int value = hashMap.get("banana");
System.out.println("Value for key 'banana': " + value);
// 특정 키가 존재하는지 확인
boolean containsKey = hashMap.containsKey("apple");
System.out.println("Contains key 'apple': " + containsKey);
// 특정 값이 존재하는지 확인
boolean containsValue = hashMap.containsValue(3);
System.out.println("Contains value 3: " + containsValue);
// 모든 키 순회
for (String key : hashMap.keySet()) {
System.out.println("Key: " + key + ", Value: " + hashMap.get(key));
}
// 모든 값 순회
for (int val : hashMap.values()) {
System.out.println("Value: " + val);
}
}
}
완주하지 못한 선수
내 풀이
동명이인이 있다는 점 때문에 다소 어렵게 느껴졌다.
처음에 내 방식대로 주저리 풀었더니 성능에서 실패해서
getOrDefault 라는 힌트를 얻어서 다시 풀었더니 쉽게 풀 수 있었다!
hash 거의 잊고 있었는데 다시 공부할 수 있어 좋았다 :)
import java.util.HashMap;
import java.util.HashSet;
class Solution {
public String solution(String[] participant, String[] completion) {
HashMap<String,Integer> hashmap = new HashMap<>();
for(String name : participant) {
hashmap.put(name, hashmap.getOrDefault(name, 0)+1);
}
for(String success : completion) {
hashmap.put(success,hashmap.getOrDefault(success, 0)-1);
}
String answer = "";
for(String key : hashmap.keySet()) {
if(hashmap.get(key) == 1) {
answer = key;
}
}
return answer;
}
}
다른사람 풀이
import java.util.HashMap;
class Solution {
public String solution(String[] participant, String[] completion) {
String answer = "";
HashMap<String, Integer> hm = new HashMap<>();
for (String player : participant) hm.put(player, hm.getOrDefault(player, 0) + 1);
for (String player : completion) hm.put(player, hm.get(player) - 1);
for (String key : hm.keySet()) {
if (hm.get(key) != 0){
answer = key;
}
}
return answer;
}
}
폰켓몬
내 풀이
생각보다 쉬워서 금방 풀었다!
import java.util.*;
class Solution {
public int solution(int[] nums) {
int answer = 0;
int getNo = nums.length / 2;
HashSet<Integer> hashset = new HashSet<>();
for (int num : nums) {
hashset.add(num);
}
if (getNo < hashset.size()) {
answer = getNo;
} else {
answer = hashset.size();
}
return answer;
}
}
다른사람 풀이
ㅠㅠ 봐도 이해도 못함
import java.util.Arrays;
import java.util.stream.Collectors;
class Solution {
public int solution(int[] nums) {
return Arrays.stream(nums)
.boxed()
.collect(Collectors.collectingAndThen(Collectors.toSet(),
phonekemons -> Integer.min(phonekemons.size(), nums.length / 2)));
}
}
전화번호 목록
내 풀이
import java.util.*;
class Solution {
public boolean solution(String[] phone_book) {
boolean answer = true;
HashSet<String> set = new HashSet<String>();
for (int i = 0; i < phone_book.length; i++) {
set.add(phone_book[i]);
}
for(String number : phone_book) {
for(int j=1; j<number.length(); j++) {
if(set.contains(number.substring(0, j)))
answer = false;
}
}
return answer;
}
}
다른사람 풀이
hashmap을 사용한 답변
class Solution {
public boolean solution(String[] phoneBook) {
boolean answer = true;
Map<String, Integer> map = new HashMap<>();
for(int i = 0; i < phoneBook.length; i++) {
map.put(phoneBook[i], i);
}
for(int i = 0; i < phoneBook.length; i++) {
for(int j = 0; j < phoneBook[i].length(); j++) {
if(map.containsKey(phoneBook[i].substring(0,j))) {
answer = false;
return answer;
}
}
}
return answer;
}
}
의상
내 풀이
엄청 어렵다고 생각했는데 방식을 알면 코드는 간단한 편이였다.
clothes에서 의상의 이름은 전혀 중요하지 않다.
의상의 종류가 몇개인지만 생각하면 된다.
예를 들어
[["yellow_hat", "headgear"], ["blue_sunglasses", "eyewear"], ["green_turban", "headgear"]]
여기에서 headgear가 2개, eyewear가 1개이다.
그럼 headgear는 A,B,선택하지 않음 => 총 3개의 경우의 수
eyewear는 C,선택하지 않음 => 총 2개의 경우의 수
그럼 조합의 수는 3*2 = 6이지만 답이 아닌 이유는
최소 한 개의 의상은 입기에 -1을 꼭 해줘야한다.
아예 HashMap에 의상의 이름은 넣지도 않았다.
의상의 종류만 넣고 나머지는 index로 체크용
import java.util.*;
class Solution {
public int solution(String[][] clothes) {
int answer = 1;
HashMap<String, Integer> map = new HashMap<>();
for (String[] clothe : clothes) {
map.put(clothe[1], map.getOrDefault(clothe[1], 0) + 1);
}
for (Integer num : map.values()) {
answer *= (num + 1);
}
return answer-1;
}
}
베스트앨범
level3는 못풀었다. 답 봐도 완전히 이해 불가. 나중에 풀자
가장 마음에 들었던 풀이로 공부하기!
프로그래머스 - 베스트앨범 (JAVA)
문제 링크 문제 설명 스트리밍 사이트에서 장르 별로 가장 많이 재생된 노래를 두 개씩 모아 베스트 앨범을 출시하려 합니다. 노래는 고유 번호로 구분하며, 노래를 수록하는 기준은 다음과 같
hy-ung.tistory.com
public class Solution {
public static class movie{
int idx;
int play;
public movie(int idx, int play) {
this.idx = idx;
this.play = play;
}
}
public static int[] solution(String[] genres, int[] plays) {
ArrayList<Integer> answer = new ArrayList<>();
// 가장 많이 플레이된 장르 선별 작업
HashMap<String, Integer> map = new HashMap<>();
for (int i = 0; i < genres.length; i++) {
map.put(genres[i], map.getOrDefault(genres[i], 0) + plays[i]);
}
// 정렬 위해서 ArrayList에 넣기
ArrayList<String> mapToGenres = new ArrayList<>();
for(String item : map.keySet()){
mapToGenres.add(item);
}
mapToGenres.sort(((o1, o2) -> map.get(o2) - map.get(o1)));
// 장르 내에서 가장 많이 플레이된 항목 선별
for (String item : mapToGenres){
ArrayList<movie> movies = new ArrayList<>();
for (int i = 0; i < genres.length; i++) {
if(item.equals(genres[i])){
movies.add(new movie(i, plays[i]));
}
}
// movie 클래스 사용(idx와 play 동시 관리 목적)
// 정렬된 장르순으로 같은 장르면 리스트에 넣어줌
movies.sort(new Comparator<movie>() {
@Override
public int compare(movie o1, movie o2) {
if(o1.play == o2.play){
return o1.idx - o2.idx;
}
return o2.play - o1.play;
}
});
// 정렬 (play수 기준 내림차순, play수 같으면 오름차순)
answer.add(movies.get(0).idx);
if(movies.size() != 1){
answer.add(movies.get(1).idx);
}
}
// List를 Array로 변환해서 답 반환
return answer.stream().mapToInt(i -> i).toArray();
}
}
'프로그래머스 (java)' 카테고리의 다른 글
프로그래머스 자바 :: 로그인 성공? (0) | 2023.11.17 |
---|---|
프로그래머스 자바 :: 합성수 찾기 (1) | 2023.11.17 |
프로그래머스 자바 :: 모의고사 (완전탐색) (0) | 2023.10.03 |
프로그래머스 자바 :: 음양 더하기 (0) | 2023.08.29 |
프로그래머스 자바 (콜라츠 추측 / 수박수박수박수박수박수? / 내적) (0) | 2023.08.26 |