[프로그래머스] 체육복 자바 코드

mango·2023년 7월 8일
0

프로그래머스 level 1

목록 보기
11/17
post-thumbnail

정답률 낮은 순으로 풀고있는데 좀 밑에 있길래 쉬울줄 알았더니 어렵구만!

* Things i leant

1. array를 ArrayList에 넣기

int[] intArray = new int[];
ArrayList<Integer> aL = new ArrayList<>();

for(int i: intArray){
	intArray.add(i);
}

2. HashMap 키 하나씩 읽기

HashMap<Integer, Boolean> hm = new HashMap<>();

for(Integer i: hm.keySets()){
	// 순서는 put한 순서

3. HashMap 값 하나씩 읽기

HashMap<Integer, Boolean> hm = new HashMap<>();

for(Boolean i: hm.values()){
	//순서는 put한 순서
}

4. 정렬이 가능한 데이터구조는?

(1). array

int[] even = {8,2,6,4,10};

Arrays.sort(even);								//오름차순
Arrays.sort(even, Collections.reverseOrder());	//내림차순

Arrays.sort(even, 2, 4);						//index 2,4 사이 자리만 정렬
// even = {8,2,4,6,10}

(2). ArrayList

ArrayList<Integer> evenAL = ArrayList<Integer>();

Collection.sort(evenAL);								//오름차순
Collection.sort(evenAL, Collections.reverseOrder());	//내림차순

//Java8 이상
evenAL.sort(Comparator.naturalOrder());				//오름차순
evenAL.sort(Comparater.reverseOrder());				//내림차순

(3) HashMap
HashMap의 경우 key든 value든 List로 변환 후 정렬하면 된다.
key는 keySet()
value는 values()

* 알고리즘

  1. lost는 도난당한 학생으로 ArrayList로 만들고 해당 학생이 있는지 빠른 접근이 필요하고 중복이 없고 삭제를 해야하므로 HashMap으로 만듦
  2. reserve는 빌려주는 학생으로 한명씩 다 읽어야하므로 ArrayList로 만듦
  3. lost와 reserve는 5번에서 체육복을 빌려줄 우선순위를 정할텐데 숫자가 마구잡이로 섞여 있을 수 있으므로 정렬을 해줌
  4. 본인이 lost에 있는지는 먼저 봐야 하므로 reserve를 하나씩 읽으면서 lost에 같은 숫자가 있으면 reserve와 lost 삭제 (본인이 도난당했다면 빌려줄 옷이 없는게 룰임)
  5. 이제 여벌이 있는데 도난당한 학생은 모두 제외 했으므로 reserve를 하나씩 읽으면서 lost에서 해당되는 번호 삭제 (우선순위는 앞번호, 본인, 뒷번호 중 어떻게 되도 상관없음)

* 자바 코드

- (1차)

import java.util.*;

class Solution {
    public int solution(int n, int[] lost, int[] reserve) {
        int answer = 0;
        ArrayList<Integer> whoReserve = new ArrayList<Integer>(reserve.length);
        ArrayList<Integer> whoLostList = new ArrayList<Integer>(lost.length);
        HashMap<Integer, Boolean> whoLost = new HashMap<>();

        for(int i: lost){
            whoLostList.add(i);   
        }
        for(int j: reserve){
            whoReserve.add(j);   
        }
        
        Collections.sort(whoLostList);
        Collections.sort(whoReserve);
        
        
        for(int i = 0; i < whoLostList.size(); i++){
            whoLost.put(whoLostList.get(i), true);
        }
        
        for(int j = 0; j < whoReserve.size(); j++){
            if(whoLost.get(whoReserve.get(j)) != null){
                whoLost.remove(whoReserve.get(j));    continue;
                }
            if(whoLost.get(whoReserve.get(j)-1) != null){
                whoLost.remove(whoReserve.get(j)-1);    continue;
                }
            if(whoLost.get(whoReserve.get(j)+1) != null){
                whoLost.remove(whoReserve.get(j)+1);    continue;
                }
        }
        
        return n - whoLost.size();
    }
}

-> 두개 정도 틀렸다.

- (2차)

import java.util.*;

class Solution {
    public int solution(int n, int[] lost, int[] reserve) {
        int answer = 0;
        ArrayList<Integer> whoReserveList = new ArrayList<Integer>(reserve.length);
        ArrayList<Integer> whoLostList = new ArrayList<Integer>(lost.length);
        HashMap<Integer, Boolean> whoReserve = new HashMap<>();
        HashMap<Integer, Boolean> whoLost = new HashMap<>();

        for(int i: lost){
            whoLostList.add(i);   
        }
        for(int j: reserve){
            whoReserveList.add(j);   
        }
        
        Collections.sort(whoLostList);
        Collections.sort(whoReserveList);
        
        
        for(int i = 0; i < whoLostList.size(); i++){
            whoLost.put(whoLostList.get(i), true);
        }
        for(int i = 0; i < whoReserveList.size(); i++){
            whoReserve.put(whoReserveList.get(i), true);
        }
        
        // Set<Integer> keys = new Set<>(whoReserve.keySet());
        for(Integer i : whoReserve.keySet()){
            if(whoLost.get(i) != null){
                whoLost.remove(i); 
                whoReserve.remove(i);
            }
        }
        for(Integer j : whoReserve.keySet()){
            if(whoLost.get(j) != null){
                whoLost.remove(j);    continue;
                }
            if(whoLost.get(j-1) != null){
                whoLost.remove(j-1);    continue;
                }
            if(whoLost.get(j+1) != null){
                whoLost.remove(j+1);    continue;
                }
        }
        
        return n - whoLost.size();
    }
}

-> 이번엔 런타임에러가 .. keySet() 안에서 for문 돌고 있는데 key를 삭제하려니 런타임 에러가 나는걸까? 결국 Reserve는 HashMap이 아니라 ArrayList에서 해결하기로 변경

- (3차) - 정답★

import java.util.*;

class Solution {
    public int solution(int n, int[] lost, int[] reserve) {
        int answer = 0;
        ArrayList<Integer> whoReserve = new ArrayList<Integer>(reserve.length);
        ArrayList<Integer> whoLostList = new ArrayList<Integer>(lost.length);
        HashMap<Integer, Boolean> whoLost = new HashMap<>();

        for(int i: lost){
            whoLostList.add(i);   
        }
        for(int j: reserve){
            whoReserve.add(j);   
        }
        
        Collections.sort(whoLostList);
        Collections.sort(whoReserve);
        
        
        for(int i = 0; i < whoLostList.size(); i++){
            whoLost.put(whoLostList.get(i), true);
        }
        
        for(int j = 0; j < whoReserve.size(); j++){
            if(whoLost.get(whoReserve.get(j)) != null){
                whoLost.remove(whoReserve.get(j));
                whoReserve.remove(whoReserve.get(j));
            }
        }
        for(int j = 0; j < whoReserve.size(); j++){
            if(whoLost.get(whoReserve.get(j)) != null){
                whoLost.remove(whoReserve.get(j));    continue;
                }
            if(whoLost.get(whoReserve.get(j)-1) != null){
                whoLost.remove(whoReserve.get(j)-1);    continue;
                }
            if(whoLost.get(whoReserve.get(j)+1) != null){
                whoLost.remove(whoReserve.get(j)+1);    continue;
                }
        }
        
        return n - whoLost.size();
    }
}

-> 나이스~

- 번외) 자바 코드(4차)

import java.util.*;

class Solution {
    public int solution(int n, int[] lost, int[] reserve) {
        int answer = 0;
        ArrayList<Integer> whoReserveList = new ArrayList<Integer>(reserve.length);
        ArrayList<Integer> whoLostList = new ArrayList<Integer>(lost.length);
        HashMap<Integer, Boolean> whoReserve = new HashMap<>();
        HashMap<Integer, Boolean> whoLost = new HashMap<>();

        for(int i: lost){
            whoLostList.add(i);   
        }
        for(int j: reserve){
            whoReserveList.add(j);   
        }
        
        Collections.sort(whoLostList);
        Collections.sort(whoReserveList);
        
        
        for(int i = 0; i < whoLostList.size(); i++){
            whoLost.put(whoLostList.get(i), true);
        }
        for(int i = 0; i < whoReserveList.size(); i++){
            whoReserve.put(whoReserveList.get(i), true);
        }
        
        for(Integer j : whoReserve.keySet()){
            if(whoLost.get(j) != null){
                whoLost.remove(j);    continue;
                }
            if(whoLost.get(j-1) != null){
                whoLost.remove(j-1);    continue;
                }
            if(whoLost.get(j+1) != null){
                whoLost.remove(j+1);    continue;
                }
        }
        
        return n - whoLost.size();
    }
}

-> 다맞고 테스트 5만 틀렸음

테스트 5 반례) n: 5, lost [4,5], reserve [3,4]
3을 읽었을때 3은 없지만 2와 4를 찾으니 4가 있어서 4를 빌려주고, 4는 5를 빌려주게되기 때문에 틀렸음

profile
앎의 즐거움을 아는 나는 mango ♪

1개의 댓글

comment-user-thumbnail
3일 전

안녕하세요!
체육복 문제 풀다가 테스트케이스가 통과가 안돼서 이래저래 구글링하다 포스팅을 보게 되었습니다.
테스트케이스 5 반례를 어떻게 찾으신걸까요? 테스트 케이스가 무엇인지 직접 추가해보고 알게 되신걸까요? 테스트 케이스 추가하는게 익숙하지 않다 보니 어떻게 반례를 찾게 되시는지 궁금해서 댓글 남깁니다! 읽어주셔서 감사합니다

답글 달기