풀이
시도1. HashMap 사용 (이름 중복시, 이름임의로 바꿔서 저장하는 방식) --> 실패
시도2. 이중 for-loop사용 --> 실패 (시간초과)
시도3. 정렬사용 --> 성공 (시간효율성은 떨어짐)
시도4. HashMap 사용 (getOrDefault 메소드 사용) --> 성공 (시간효율 좋음)
시도1. HashMap사용 (구현 실패)
이름 중복시, 이름 임의로 바꿔서 저장하는 방식
시도2. 이중 for-loop사용
코드:
import java.util.*;
class Solution {
public String solution(String[] participant, String[] completion) {
for (int i=0; i<completion.length; i++) {
for (int j=0; j<participant.length; j++) {
if (completion[i].equals(participant[j])) {
participant[j] = "";
break;
}
}
}
String answer = "";
for (String s: participant) {
if (!s.equals("")) {
answer = s;
}
}
return answer;
}
}
결과:
시도3. 정렬사용
코드:
import java.util.*;
class Solution {
public String solution(String[] participant, String[] completion) {
Arrays.sort(participant);
Arrays.sort(completion);
String answer ="";
for (int i=0; i<completion.length; i++) {
if (!participant[i].equals(completion[i])){
answer = participant[i];
break;
}
}
if (answer.equals("")) {
answer = participant[participant.length-1];
}
return answer;
}
}
결과:
시도4. HashMap사용
* getOrDefault 메소드 (아주 유용하게 쓰일듯)
* EntrySet 메소드
(Key, value) 구조의 Entry을 저장하는 Set 자료구조
Set이므로 Map에선 불가한 Iterator로 멤버 하나씩 접근가능
코드:
import java.util.Map.Entry;
import java.util.*;
class Solution {
public String solution(String[] participant, String[] completion) {
HashMap<String, Integer> map = new HashMap<>();
for (String player: participant) {
map.put(player, map.getOrDefault(player, 0) + 1);
}
for (String player: completion) {
map.put(player, map.getOrDefault(player, 0) - 1);
}
Set<Entry<String, Integer>> set = map.entrySet();
Iterator it = set.iterator();
String answer = "";
while(it.hasNext()) {
Entry<String, Integer> entry = (Entry)it.next();
if (entry.getValue() == 1) {
answer = entry.getKey();
break;
}
}
return answer;
}
}
결과:
'알고리즘 > 자료구조' 카테고리의 다른 글
프로그래머스[자바] - 전화번호 목록 (0) | 2022.06.25 |
---|---|
프로그래머스[자바] - 기능개발 (0) | 2022.06.24 |