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 |
'프로그래밍 > 알고리즘 연습' 카테고리의 다른 글
[TopCoder,전체 탐색]재미있는 수학 (0) | 2019.02.10 |
---|---|
[TopCoder,전체 탐색]암호 (0) | 2019.02.10 |
[Topcoder] 키위 주스 (0) | 2019.02.10 |
[JAVA]알고리즘 풀 때 알고 있으면 좋은 지식들 (0) | 2019.02.10 |
(2018년)KAKAO BLIND RECRUITMENT - 무지의 먹방 라이브(틀림) (0) | 2019.01.30 |