본문 바로가기
프로그래밍/알고리즘 연습

[TopCoder, 전체 탐색]즐거운 파티

by mrvan 2019. 2. 10.

1. 내가 짠 코드

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
public class test {
    public static void main(String[] args){
        test test = new test();
        String[] first = {"snakes","programming","cobra","monty"};
        String[] second = {"python","python","anaconda","python"};
//        String[] first = {"variety","diversity","loquacity","courtesy"};
//        String[] second = {"talking","speaking","discussion","meeting"};
//        String[] first = {"fishing","gardening","swimming","fishing"};
//        String[] second = {"hunting","fishing","fishing","biting"};
        int answer = test.bestInvitation(first, second);
        System.out.println(answer);
    }
    public int bestInvitation(String[] first, String[] second){
        int max = 0;
        int fa;
        int sa;
        for(int i =0; i< first.length;i++){
            fa=0;
            sa=0;
            for(int j=0;j<second.length;j++){
                if(first[i].equals(first[j])||first[i].equals(second[j]))
                    fa++;
                if(second[i].equals(first[j])||second[i].equals(second[j]))
                    sa++;
            }
            max = Math.max(max,sa);
            max = Math.max(max,fa);
        }
        return max;
    }
 
}
 
 
----------------------------결과-------------------------------
3
 
cs


2. 개선 코드 : 연관 배열(HashMap) 사용

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
38
import java.util.HashMap;
 
public class test {
    public static void main(String[] args){
        test test = new test();
//        String[] first = {"snakes","programming","cobra","monty"};
//        String[] second = {"python","python","anaconda","python"};
        String[] first = {"variety","diversity","loquacity","courtesy"};
        String[] second = {"talking","speaking","discussion","meeting"};
//        String[] first = {"fishing","gardening","swimming","fishing"};
//        String[] second = {"hunting","fishing","fishing","biting"};
        int answer = test.bestInvitation(first, second);
            System.out.println(answer);
    }
    public int bestInvitation(String[] first, String[] second){
        int ans=0;
        HashMap<String, Integer> dic = new HashMap<String, Integer>();
        for(int i =0; i<first.length;i++){
            if(dic.containsKey(first[i]))
                dic.put(first[i],dic.get(first[i])+1);
            else
                dic.put(first[i],1);
            if(dic.containsKey(second[i]))
                dic.put(second[i],dic.get(second[i])+1);
            else
                dic.put(second[i],1);
        }
 
        for(String key : dic.keySet()){
            ans = Math.max(ans,dic.get(key));
        }
        return ans;
    }
 
}
 
--------------------------결과-----------------------------------
1
cs