가자공부하러!

탐욕법 - 체육복 (프로그래머스) - 완료 본문

공부/알고리즘

탐욕법 - 체육복 (프로그래머스) - 완료

오피스엑소더스 2019. 5. 15. 19:39

https://programmers.co.kr/learn/courses/30/lessons/42862


2019-05-15 실패 ㅠㅠ 


문제 : 


내 코드 : 

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
    public int solution(int n, int[] lost, int[] reserve) {
        int i = 0, j = 0, cnt=0;
        int answer = 0;
        int getNew = 0 ;
        int lostLength=lost.length;
        int reserveLength=reserve.length;
        int[] lost1 = lost;
        int[] reserve1 = reserve;
        for(i=0; i<lostLength; i++) {
            for(j=cnt; j<reserveLength; j++) {
                if(lost1[i] >= (reserve1[j]-1&& lost1[i]<=(reserve1[j]+1) ) {
                    //lost의 i번 째 값이 reserve의 j값과 1차이나면
                    getNew++;
                    //체육복 빌린사람 수 +1
                    reserve1[j]=0;
                    //체육복 빌려준놈은 0
                    cnt++;
                    break;
                }
            }            
        }
        //총 참가 인원 = (전체인원-체육복안가져온놈)+빌린놈
        answer = (n-lostLength) + getNew;
        return answer;
    }
cs


수행결과



구글링 코드 : 

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
32
33
34
35
36
37
class Solution {
    public int solution(int n, int[] lost, int[] reserve) {
        int answer=0;
        int[] student=new int[n+1]; // 1~n까지의 인덱스를 사용!
        
        // student 배열 초기화
        for(int i=1;i<=n;i++)
            student[i]=1;
        for(int l:lost){
            student[l]--;
        }
        for(int r:reserve){
            student[r]++;
        }
        
        // 없는 친구끼리 빌려주기
        for(int i=1;i<=n;i++){
            if(student[i]==0){
                if(i+1<=&& student[i+1]==2){
                    student[i+1]--;
                    student[i]++;
                } else if(i-1>=1 && student[i-1]==2){
                    student[i-1]--;
                    student[i]++;
                }
            }
        }
        
        // 체육복을 1개이상 가지고 있으면 수업을 들을 수 있음
        for(int i=1;i<=n;i++){
            if(student[i]>=1)
                answer++;
        }
        
        return answer;
    }
}
cs

출처 : https://heunnnn.github.io/%ED%83%90%EC%9A%95%EB%B2%95(1)-%EC%B2%B4%EC%9C%A1%EB%B3%B5/




 

 

 

 




맨 위로

Comments