정수 배열 numbers가 주어집니다. numbers에서 서로 다른 인덱스에 있는 두 개의 수를 뽑아 더해서 만들 수 있는 모든 수를 배열에 오름차순으로 담아 return 하도록 solution 함수를 완성해주세요.
numbers: [2,1,3,4,1]
result: [2,3,4,5,6,7]
2중 for문을 사용하여 같은 인덱스가 아닐 경우에만 값을 더했다. 그 값은 hash의 key값으로 해시맵에 key가 존재한다면 값+1을 해주었고, 아니면 1을 value에 넣어주었다. 마지막으로 해시 키 만큼의 배열을 만들고 담아준 뒤 정렬을 해주었다.
class Solution {
public int[] solution(int[] numbers) {
HashMap<Integer, Integer> hash = new HashMap<>();
for(int i=0;i<numbers.length;i++){
for(int j=0;j<numbers.length;j++){
if(i==j) continue;
int sum=numbers[i]+numbers[j];
if(hash.containsKey(sum)) {
hash.put(sum, hash.get(sum)+1);
}else {
hash.put(sum, 1);
}
}
}
int[] answer = new int[hash.keySet().size()];
int i=0;
for(int key:hash.keySet()) {
answer[i++]=key;
}
Arrays.sort(answer);
return answer;
}
}
- 저번 완주하지 못한 선수 풀이 생각으로 hash로 풀이를 했다..! 이때 map의 value값은 의미있는 값이 필요가 없기때문에 아무 값이나 넣어줘도 되고.. set으로 풀이하는게 더 효율적이다!
class Solution {
public int[] solution(int[] numbers) {
TreeSet<Integer> set = new TreeSet<>();
for(int i=0; i<numbers.length; i++) {
for(int j=i+1; j<numbers.length; j++) {
set.add(numbers[i] + numbers[j]);
}
}
return set.stream().mapToInt(Integer::intValue).toArray();
}
}
[출처] 프로그래머스