일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | |
7 | 8 | 9 | 10 | 11 | 12 | 13 |
14 | 15 | 16 | 17 | 18 | 19 | 20 |
21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 | 29 | 30 | 31 |
- kotlin
- 전위 중위 후위
- 서브모듈 yml
- 프로그래머스
- 백준 8979번 올림픽 S5 자바
- 백준 11725번 트리의 부모 찾기
- 코틀린기초
- toUpperCase
- Java
- 포인트 컷
- 백준 2206번 벽 부수고 이동하기 G3
- hash
- replace()
- 프로그래머스 java
- 스프링 다중프로필
- HashMap
- map
- StringBuilder
- dp
- 스프링 on-profile
- append
- 백준 2589번 보물섬 G5
- HashSet
- 백준 1240번 노드사이의 거리
- 백준 1600번 말이 되고픈 원숭이
- 백준 2660번 회장뽑기 G5
- 백준 1967번 트리의 지름 G4 자바
- Stack
- 프로그래머스 자바
- StringTokenizer
- Today
- Total
말하는 컴공감자의 텃밭
프로그래머스 추억점수 - 자바(java) HashMap 본문
Map 쓰는 문제를 찾다가 줍게된 문제이다.
name 갯수와 같은 yearning에 점수가 담겨있고, 해당 이름순번에 맞는 점수가 담겨있다.
photo에는 이름이 2차원 배열로 담겨있고, 이름을 점수로 변환하여 리턴하면 되는 문제이다.
for문 반복으로 풀수도 있지만 시간복잡도가 n^3이라 map을 사용하기로 했다.
이름 중복이 없어서 Hash는 굳이 안써도 되었지만 사용했다.
import java.util.*;
class Solution {
public int[] solution(String[] name, int[] yearning, String[][] photo) {
int[] answer = new int[photo.length];
HashMap <String,Integer> map = new HashMap<>(); // HashMap 선언 key엔 이름이므로 string
for(int i = 0; i<name.length; i++){ // 반복문으로 map에 name과 yearning값 넣어주기
map.put(name[i],yearning[i]);
}
for(int i = 0; i<photo.length; i++){
int score = 0;
for(int j = 0; j<photo[i].length; j++){
String names = photo[i][j]; // names 선언후 반복문으로
if(map.containsKey(names)){ // map에 있는 names이라면
score +=map.get(names); // score에 map.get으로 Value값을 더해준다.
}
answer[i] = score; // 결과 값 넣어주기.
}
}
return answer;
}
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | import java.util.*; class Solution { public int[] solution(String[] name, int[] yearning, String[][] photo) { int[] answer = new int[photo.length]; HashMap <String,Integer> map = new HashMap<>(); for(int i = 0; i<name.length; i++){ map.put(name[i],yearning[i]); } for(int i = 0; i<photo.length; i++){ int score = 0; for(int j = 0; j<photo[i].length; j++){ String names = photo[i][j]; if(map.containsKey(names)){ score +=map.get(names); } answer[i] = score; } } return answer; } } | cs |
물론 간단하게 하나하나 비교하는 방식도 존재한다. 다만 속도가 굉장히 느린편편
'알고리즘 > Programmers - Java' 카테고리의 다른 글
프로그래머스 최대값 만들기 - 자바(java) (0) | 2023.05.26 |
---|---|
프로그래머스 달리기 경주 <6점> - 자바(java) HashMap (0) | 2023.05.20 |
프로그래머스 개인정보 수집 유효기간 <4점> - 자바(java) ArrayList (0) | 2023.05.20 |
프로그래머스 구슬을 나누는 경우의 수 <7점> - 자바(java) 조합 Biginteger (1) | 2023.05.13 |
프로그래머스 코드처리하기 <6점> - 자바(java) StringBuilder, append, charAt (0) | 2023.05.13 |