๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm

[Programmers] - ๋‘ ๊ฐœ ๋ฝ‘์•„์„œ ๋”ํ•˜๊ธฐ

by ์ฃผ๋ฐœ2 2020. 9. 20.
๋ฐ˜์‘ํ˜•

programmers.co.kr/learn/courses/30/lessons/68644

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ๋‘ ๊ฐœ ๋ฝ‘์•„์„œ ๋”ํ•˜๊ธฐ

 

programmers.co.kr

 

 

์ฝ”๋“œ

import java.util.*;

class Solution {
    public static int[] solution(int[] numbers) {
        int numbersLen = numbers.length;
        Set<Integer> hashSet = new HashSet<>();
        
        for(int i=0; i<numbersLen-1; i++) {
        	for(int j=1; j<numbersLen; j++) {
        		if(i != j) {
        			hashSet.add(numbers[i] + numbers[j]);        			
        		}
        	}
        }
        
        List<Integer> list = new ArrayList<>(hashSet);
        Collections.sort(list);
        
        return list.stream().mapToInt(i -> i).toArray();
    }
}

ํ’€์ด

 

1. ์ฃผ์–ด์ง„ ๋ฐฐ์—ด์˜ ๋ชจ๋“  ์ธ๋ฑ์Šค์— ๋Œ€ํ•ด ๋”ํ•˜๋ฉด์„œ HashSet์— ๋„ฃ๋Š”๋‹ค.

  - HashSet์€ ์ค‘๋ณต์ด ์ œ๊ฑฐ๊ฐ€ ๋˜๋ฏ€๋กœ, ์ค‘๋ณต์— ๋Œ€ํ•ด ์‹ ๊ฒฝ์“ธ ํ•„์š”๊ฐ€ ์—†์Œ!

        for(int i=0; i<numbersLen-1; i++) {
        	for(int j=1; j<numbersLen; j++) {
        		if(i != j) {
        			hashSet.add(numbers[i] + numbers[j]);        			
        		}
        	}
        }

 

 

2. HashSet to List ๋กœ ๋ณ€ํ™˜ํ•œ ํ›„, ์ •๋ ฌ์„ ํ•œ๋‹ค.

        List<Integer> list = new ArrayList<>(hashSet);
        Collections.sort(list);

 

 

3. List์˜ ์ œ๋„ค๋ฆญ ํƒ€์ž…์ด Integer์ด๋ฏ€๋กœ, int๋กœ ๋ณ€ํ™˜ํ•œ๋‹ค.

        return list.stream().mapToInt(i -> i).toArray();

 

๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€