-
프로그래머스- 완주하지 못한 선수컴퓨터 공부/JAVA 2020. 4. 3. 17:17
https://programmers.co.kr/learn/courses/30/lessons/42576
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
해시 맵 사용
import java.util.*; class Solution { public String solution(String[] participant, String[] completion) { String answer = ""; HashMap<String,Integer> runner = new HashMap<String,Integer>(); for(int i=0;i<participant.length;i++) if(!runner.containsKey(participant[i])) runner.put(participant[i],1); else runner.put(participant[i],runner.get(participant[i])+1); for(int i=0;i<completion.length;i++) { runner.put(completion[i],runner.get(completion[i])-1); } for(int i =0;i<participant.length;i++) { if(runner.get(participant[i])!=0)answer=participant[i]; } return answer; } }
1. 일단 (참가자 이름, 1)로 초기화,
해쉬 맵은 동일 키 존재 불가!! -> 같은 키로 접근하면 값이 갱신 됨
(새로운 item이 추가되지 않고 값만 바뀜!!)
--> 동명이인은 해당 값 +1 (동명이인이 3명이면 그 이름의 값은 3)
2. 완주한 사람은 해당 값 -1
--> 완주했으면 해당 값은 0이 됨
3. 값이 0이 아니면 완주 못한 사람
다른 코드 -> 정렬해서 하나씩 비교
더보기Array.sort(participant);
Array.sort(completion);
for(int i=0;i<completion.length;i++) {
if(!participant[i].equals(completion[i])) {
return participant[i];
}
}
for(String part : participant) {
if(hm.get(part)==null)
hm.put(part,1)
}
}
'컴퓨터 공부 > JAVA' 카테고리의 다른 글
String -> char[] ->int (0) 2020.05.23 자바 - 스택, 큐 정리 (0) 2020.05.23 HashMap<K,V> (0) 2020.03.28 Iterator -> 순차 검색 (0) 2020.03.28 ArrayList vs. LinkedList vs. Vector, 제너릭 함수 (0) 2020.03.28