https://programmers.co.kr/learn/courses/30/lessons/42576
배열로 풀이 --> 실패
package com.company;
import java.util.ArrayList;
import java.util.Arrays;
public class programmers {
public static void main(String[] args) {
//https://programmers.co.kr/learn/courses/30/lessons/42576
String[] participant = {"mislav", "stanko", "mislav", "ana"};
String[] completion = {"stanko", "ana", "mislav"};
String result = Solution.solution(participant,completion);
}
static class Solution {
public static String solution(String[] participant, String[] completion) {
String answer = "";
//System.out.println(participant);// 출력: [Ljava.lang.String;@4554617c 못씀
//Arrays.toString(participant);//출력: 글씨 안나옴
//System.out.println(Arrays.toString(participant));// 정렬 전: [leo, kiki, eden]
Arrays.sort(participant);// 정렬
//System.out.println(Arrays.toString(participant));// 정렬 후: [eden, kiki, leo]
Arrays.sort(completion);// 정렬
//System.out.println(Arrays.toString(completion));// 정렬 후: [eden, kiki]
ArrayList<String> list_participant = new ArrayList<String>(Arrays.asList(participant)); // array -> arrayList 형 변환
//System.out.println(list_participant);//[eden, kiki, leo]
ArrayList<String> list_completion = new ArrayList<String>(Arrays.asList(completion)); // array -> arrayList 형 변환
//System.out.println(list_completion);//[eden, kiki]
// contains 사용하려면 arrayList 형 변환 필수
for(int i=0; i<list_participant.size(); i++){
boolean a = list_completion.contains(list_participant.get(i));// 대상 - 단어
if(!a) {
answer = list_participant.get(i);
break;
}
}
if(answer==""){//동명이인
for(int i=0; i<completion.length; i++){
String temp1 = participant[i];
String temp2 = completion[i];
if(temp1!=temp2){
answer = participant[i];
}
}
}
//System.out.println(answer);//leo
return answer;
}
}
}
다른 사람 배열 -> 성공
import java.util.*;
class Solution {
public String solution(String[] participant, String[] completion) {
Arrays.sort(participant);
Arrays.sort(completion);
int i;
for ( i=0; i<completion.length; i++){
if (!participant[i].equals(completion[i])){
return participant[i];
}
}
return participant[i];
}
}
HashMap -> 성공
import java.util.*;
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;
break;
}
}
return answer;
}
}
'알고리즘 > 알고리즘' 카테고리의 다른 글
[프로그래머스][정렬]가장 큰 수 (0) | 2021.09.28 |
---|---|
[프로그래머스][정렬][k번째 수] (0) | 2021.09.28 |
[백준] No Duplicates (0) | 2021.09.27 |
[백준] 숫자의 개수 (0) | 2021.09.27 |
[백준] 평균은 넘겠지 (0) | 2021.09.27 |