코딩테스트 풀이/JAVA
[LeetCode/Easy] 599. Minimum Index Sum of Two Lists
무지맘
2023. 3. 7. 12:35
1. Input
1) String[] list1
2) String[] list2
2. Output
1) 두 배열의 공통 문자열이 있을 때, 그 인덱스의 합이 최소가 되는 문자열을 담은 배열을 반환
- 인덱스의 합이 최소가 되는 문자열이 여러개라면 순서에 상관없이 담아서 반환
3. Constraint
1) 1 <= list1.length, list2.length <= 1000
2) 1 <= list1[i].length, list2[i].length <= 30
3) 두 배열의 문자열은 공백문자와 영어 대소문자로 이루어져 있다.
4) 각 배열에는 중복 문자열이 없다.
5) 두 배열의 공통 문자열은 최소 1개 이상 있다.
4. Example
Input: list1 = ["happy","sad","good"], list2 = ["sad","happy","good"] -> Output: ["sad","happy"]
설명:
- happy의 인덱스 합은 0 + 1 = 1
- sad의 인덱스 합은 1 + 0 = 1
- good의 인덱스 합은 2 + 2 = 4
- 합의 최소는 1이므로 ["sad","happy“] 또는 [”happy“,”sad“]를 반환한다.
5. Code
1) 첫 코드(2023/03/07)
int min = list1.length + list2.length;
HashMap<String,Integer> m = new HashMap<String,Integer>();
for(int i=0 ; i<list1.length ; i++){
for(int j=0 ; j<list2.length ; j++){
if(list1[i].equals(list2[j])){
if(i+j<=min){
min = i+j;
m.put(list1[i],i+j);
}
break;
}
}
}
ArrayList<String> answer = new ArrayList<String>();
Iterator it = m.entrySet().iterator();
while(it.hasNext()){
Map.Entry e = (Map.Entry)it.next();
if((int)e.getValue()==min)
answer.add((String)e.getKey());
}
return answer.toArray(new String[0]);