Back-end/Algorithm

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ๋‘ ๊ฐœ ๋ฝ‘์•„์„œ ๋”ํ•˜๊ธฐ (java)

Nellie Kim 2023. 8. 8. 01:34
728x90

๐Ÿ’‍โ™€๏ธ  ๋ฌธ์ œ ์„ค๋ช…

์ •์ˆ˜ ๋ฐฐ์—ด numbers๊ฐ€ ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค. numbers์—์„œ ์„œ๋กœ ๋‹ค๋ฅธ ์ธ๋ฑ์Šค์— ์žˆ๋Š” ๋‘ ๊ฐœ์˜ ์ˆ˜๋ฅผ ๋ฝ‘์•„ ๋”ํ•ด์„œ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋Š” ๋ชจ๋“  ์ˆ˜๋ฅผ ๋ฐฐ์—ด์— ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ๋‹ด์•„ return ํ•˜๋„๋ก solution ํ•จ์ˆ˜๋ฅผ ์™„์„ฑํ•ด์ฃผ์„ธ์š”.


โŒ ์ œํ•œ์‚ฌํ•ญ

  • numbers์˜ ๊ธธ์ด๋Š” 2 ์ด์ƒ 100 ์ดํ•˜์ž…๋‹ˆ๋‹ค.
    • numbers์˜ ๋ชจ๋“  ์ˆ˜๋Š” 0 ์ด์ƒ 100 ์ดํ•˜์ž…๋‹ˆ๋‹ค.

 

 

๐Ÿ’ก  ์ž…์ถœ๋ ฅ ์˜ˆ

 

์ž…์ถœ๋ ฅ ์˜ˆ #1

  • 2 = 1 + 1 ์ž…๋‹ˆ๋‹ค. (1์ด numbers์— ๋‘ ๊ฐœ ์žˆ์Šต๋‹ˆ๋‹ค.)
  • 3 = 2 + 1 ์ž…๋‹ˆ๋‹ค.
  • 4 = 1 + 3 ์ž…๋‹ˆ๋‹ค.
  • 5 = 1 + 4 = 2 + 3 ์ž…๋‹ˆ๋‹ค.
  • 6 = 2 + 4 ์ž…๋‹ˆ๋‹ค.
  • 7 = 3 + 4 ์ž…๋‹ˆ๋‹ค.
  • ๋”ฐ๋ผ์„œ [2,3,4,5,6,7] ์„ return ํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.



์ž…์ถœ๋ ฅ ์˜ˆ #2

  • 2 = 0 + 2 ์ž…๋‹ˆ๋‹ค.
  • 5 = 5 + 0 ์ž…๋‹ˆ๋‹ค.
  • 7 = 0 + 7 = 5 + 2 ์ž…๋‹ˆ๋‹ค.
  • 9 = 2 + 7 ์ž…๋‹ˆ๋‹ค.
  • 12 = 5 + 7 ์ž…๋‹ˆ๋‹ค.
  • ๋”ฐ๋ผ์„œ [2,5,7,9,12] ๋ฅผ return ํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.

 

๐Ÿ‘ฉ ๋‚ด ํ’€์ด

import java.util.*;

class Solution {
    public int[] solution(int[] numbers) {
        HashSet<Integer> set = new HashSet<>();

        for (int i = 0; i < numbers.length - 1; i++) {
            for (int j = i+1; j < numbers.length; j++) {
                int a = numbers[i] + numbers[j];
                set.add(a);
            }
        }
        
        // set์„ Integer๋ฐฐ์—ด๋กœ
        Integer[] array = set.toArray(new Integer[0]);

        // Integer๋ฐฐ์—ด์„ int๋ฐฐ์—ด๋กœ
        int[] intArray = Arrays.stream(array).mapToInt(Integer::intValue).toArray();
        Arrays.sort(intArray);

        return intArray;
    }
}

 

๐Ÿง‘ ๋‹ค๋ฅธ ์‚ฌ๋žŒ ํ’€์ด

import java.util.HashSet;
import java.util.Set;

class Solution {
     public int[] solution(int[] numbers) {
        Set<Integer> set = new HashSet<>();

        for(int i=0; i<numbers.length; i++) {
            for(int j=i+1; j<numbers.length; j++) {
                set.add(numbers[i] + numbers[j]);
            }
        }

       // set์„ ์ •๋ ฌ์‹œํ‚ค๊ณ , int๋ฐฐ์—ด๋กœ ๋ณ€ํ™˜ํ•˜๊ธฐ
        return set.stream().sorted().mapToInt(Integer::intValue).toArray();
    }
}

์ข‹์•„์š”๋ฅผ ๊ฐ€์žฅ ๋งŽ์ด ๋ฐ›์€ ํ’€์ด์ด๋‹ค. ๋‚ด ํ’€์ด๋ž‘ ๋น„์Šทํ•˜๋‹ค. 

stream์—์„œ ๋ฐ”๋กœ sorted()๋ฅผ ํ•ด์ฃผ๋„๋ก ํ•˜์ž. stream์„ ๊ณต๋ถ€๋ฅผ ๋” ํ•ด์•ผ๊ฒ ๋‹ค.