๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm๐Ÿฐ/ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

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

by Jouureee 2021. 2. 26.

๋ฌธ์ œ :

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

 

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

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

programmers.co.kr

๋ถ„์„ :

input vector : numbers

output vector : answer

 

ex>

input        output 
[2,1,3,4,1] [2,3,4,5,6,7]
[5,0,2,7] [2,5,7,9,12]

 

๊ฐ€ ์ฃผ์–ด์งˆ ๋•Œ 

์ฒซ๋ฒˆ์งธ for ๋ฌธ : inter ๋Š” ๋ฐ˜๋ณตํ•  ๊ฐ„๊ฒฉ์ด๋‹ค. 1 ~ size-1 ๋ฒ”์œ„๋ฅผ ๊ฐ€์ง„๋‹ค.

๋‘๋ฒˆ์งธ for ๋ฌธ : j๋Š” ๋Œ ์ธ๋ฑ์Šค, j์˜ ๋ฒ”์œ„๋Š” ๊ฐ„๊ฒฉ ๋งˆ์ง€๋ง‰ ์›์†Œ๊ฐ€ ์ฐธ์กฐ๋˜๋Š” ๊ณณ ๊นŒ์ง€ ๋”ฐ๋ผ์„œ 0 ~ size - inter ๋‹ค.

find ํ•จ์ˆ˜ ( vector.begin(), vector.end(), ์ฐพ์„ ๊ฐ’)

์›์†Œ์˜ ์ธ๋ฑ์Šค ๋ฐ˜ํ™˜ํ•˜๋Š”๋ฐ answer์— ์—†์„ ๊ฒฝ์šฐ answer.end()์™€ ๊ฐ™์€ ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค. 

 

๋งˆ์ง€๋ง‰์— ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ sort 

 

c++ ์ฝ”๋“œ :

#include <string>
#include <vector>
#include <algorithm>
#include <iostream>

using namespace std;

vector<int> solution(vector<int> numbers) {
     vector<int> answer;
     for(int inter = 1; inter < (int)numbers.size(); inter++){
         for(int j = 0; j < (int)(numbers.size()) - inter; j++){
            int temp = numbers[j] + numbers[j+inter];
             if(find(answer.begin(), answer.end(), temp) == answer.end()){
                answer.push_back(temp);
             }
         }  
     }
    sort(answer.begin(), answer.end());
             
     
    return answer;
}

๋ ˆ๋ฒจ 1๋„ ๋ฒ„๊ฒ๋‹ค ์กฐ๊ธˆ์”ฉ ์ž˜ ์กฐ์ ธ๋ณด์ž ํ•˜ํ•˜

 

๋Œ“๊ธ€