[Programmers] Lv2. ์—ฐ์†๋œ ๋ถ€๋ถ„ ์ˆ˜์—ด์˜ ํ•ฉ | C++

2023. 6. 27. 18:10ใ†Coding Test/Programmers

๐Ÿ”—๋ฌธ์ œ ๋ณด๋Ÿฌ๊ฐ€๊ธฐ
 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

 

๐Ÿ‘จ‍๐Ÿ’ปํ’€์ด ๊ณผ์ •

 

์ž…๋ ฅ ๋ฐ์ดํ„ฐ ํฌ๊ธฐ๊ฐ€ 1,000,000๊ฐœ์ด๋‹ˆ ๋‹น์—ฐํžˆ \( O(n^2) \)์œผ๋กœ๋Š” ๋ชป ํ’‰๋‹ˆ๋‹ค. ์ฆ‰, ์ด์ค‘ ๋ฐ˜๋ณต๋ฌธ์œผ๋กœ๋Š” ์–ด๋ ต๊ฒ ๋‹ค๊ณ  ์ƒ๊ฐํ•˜์˜€์Šต๋‹ˆ๋‹ค. ๊ทธ๋ž˜์„œ ์ €๋Š” ๋‘ ๊ฐœ์˜ ์ธ๋ฑ์Šค ๋ณ€์ˆ˜๋ฅผ ํ†ตํ•ด, ๋ฐ˜๋ณต๋ฌธ์„ ํ•œ ๋ฒˆ๋งŒ ๋Œ๋„๋ก ํ’€์ด๋ฅผ ๊ตฌ์ƒํ•˜์˜€์Šต๋‹ˆ๋‹ค.

 

  • ์‹œ์ž‘ ์ธ๋ฑ์Šค(startIdx), ๋ ์ธ๋ฑ์Šค(lastIdx), ํ•ฉ๊ณ„ ๋ณ€์ˆ˜(sum)๋ฅผ ๋ชจ๋‘ 0์œผ๋กœ ์ดˆ๊ธฐํ™”ํ•˜์—ฌ ์„ ์–ธํ•ฉ๋‹ˆ๋‹ค.
  • startIdx <= lastIdx ์ด๊ณ , lastIdx < sequence.size()๋ผ๋ฉด, while๋ฌธ์„ ๋Œ์•„์ค๋‹ˆ๋‹ค.
    • sum + sequence[lastIdx] == k๋ผ๋ฉด, ๋‹ต์˜ ํ›„๋ณด ์ค‘ ํ•˜๋‚˜์ด๋ฏ€๋กœ ๋ณ„๋„๋กœ ์ €์žฅํ•ด ๋†“์Šต๋‹ˆ๋‹ค.
    • sum + sequence[lastIdx] < k๋ผ๋ฉด, sum += sequnece[lastIdx++]
    • sum + sequence[lastIdx] >= k๋ผ๋ฉด, sum -= sequnece[startIdx++]
    • ์œ„์™€ ๊ฐ™์ด ์กฐ๊ฑด๋ฌธ๋“ค์„ ์ง€์ •ํ•˜์—ฌ ๋ฐ˜๋ณตํ•ด์ค๋‹ˆ๋‹ค.
  • ๋ฐ˜๋ณต๋ฌธ์ด ๋๋‚ฌ๋‹ค๋ฉด, ์งง์€ ๊ธธ์ด์˜ ์ˆ˜์—ด์ด ์•ž ์ชฝ์œผ๋กœ ๊ฐ€๋„๋ก ์ •๋ ฌํ•ด์ค๋‹ˆ๋‹ค.
    • ๊ธธ์ด๊ฐ€ ๊ฐ™๋‹ค๋ฉด, ์‹œ์ž‘ ์ธ๋ฑ์Šค๊ฐ€ ์ž‘์€ ๊ฒŒ ์•ž์œผ๋กœ ๊ฐ€๋„๋ก ํ•ด์ค๋‹ˆ๋‹ค.
  • ์ •๋ ฌ ํ›„, ์ฒซ ๋ฒˆ์งธ ํ›„๋ณด์˜ ์‹œ์ž‘ ์ธ๋ฑ์Šค์™€ ๋ ์ธ๋ฑ์Šค๋ฅผ ๋ฐฐ์—ด์— ๋‹ด์•„ ๋ฆฌํ„ดํ•ด์ค๋‹ˆ๋‹ค.

 

โœ๏ธ์†Œ์Šค ์ฝ”๋“œ ๋ฐ ๊ฒฐ๊ณผ

#include <vector>
#include <algorithm>
using namespace std;

bool Compare(const pair<int, int>& n1, const pair<int, int>& n2) {
    int n1Difference = abs(n1.first - n1.second);
    int n2Difference = abs(n2.first - n2.second);

    if (n1Difference == n2Difference)
        return n1.first < n2.first;
    return n1Difference < n2Difference;
}

vector<int> solution(vector<int> sequence, int k) {
    vector<pair<int, int>> candidates;
    int startIdx = 0, lastIdx = 0;
    int sum = 0;

    while (startIdx <= lastIdx and lastIdx < sequence.size()) {
        int nextSum = sum + sequence[lastIdx];
        
        if (nextSum == k)
            candidates.emplace_back(startIdx, lastIdx);

        if (nextSum < k)
            sum += sequence[lastIdx++];
        else
            sum -= sequence[startIdx++];
    }

    sort(candidates.begin(), candidates.end(), Compare);
    vector<int> answer {candidates[0].first, candidates[0].second};
    return answer;
}

 

 

728x90
๋ฐ˜์‘ํ˜•