[C++] 투 포인터(Two Pointer)

2020. 5. 1. 16:32Β·πŸ“ Computer Science/✏ Algorithm

투 ν¬μΈν„°(Two Pointer)

1차원 λ°°μ—΄μ—μ„œ 각자 λ‹€λ₯Έ μ›μ†Œλ₯Ό 가리킀고 μžˆλŠ” 2개의 포인터λ₯Ό μ‘°μž‘ν•˜μ—¬ μ›ν•˜λŠ” 값을 μ–»λŠ” μ•Œκ³ λ¦¬μ¦˜μ΄λ‹€.

 

투 포인터

 

문제

 

https://www.acmicpc.net/problem/2003

 

2003번: μˆ˜λ“€μ˜ ν•© 2

첫째 쀄에 N(1≤N≤10,000), M(1≤M≤300,000,000)이 μ£Όμ–΄μ§„λ‹€. λ‹€μŒ μ€„μ—λŠ” A[1], A[2], …, A[N]이 곡백으둜 λΆ„λ¦¬λ˜μ–΄ μ£Όμ–΄μ§„λ‹€. 각각의 A[x]λŠ” 30,000을 λ„˜μ§€ μ•ŠλŠ” μžμ—°μˆ˜μ΄λ‹€.

www.acmicpc.net

#include <iostream>
using namespace std;

int arr[10000];

int main()
{
	int N, M;
	cin >> N >> M;
	for (int i = 0; i < N; i++)
		cin >> arr[i];

	int ans = 0, sum = 0;
	int start = 0, end = 0;
	while (1) {
		if (sum >= M)
			sum -= arr[start++];
		else if (end == N)
			break;
		else
			sum += arr[end++];

		if (sum == M)
			ans++;
	}
	cout << ans;
}

 

https://www.acmicpc.net/problem/1806

 

1806번: λΆ€λΆ„ν•©

문제 10,000 μ΄ν•˜μ˜ μžμ—°μˆ˜λ‘œ 이루어진 길이 N짜리 μˆ˜μ—΄μ΄ μ£Όμ–΄μ§„λ‹€. 이 μˆ˜μ—΄μ—μ„œ μ—°μ†λœ μˆ˜λ“€μ˜ λΆ€λΆ„ν•© 쀑에 κ·Έ 합이 S 이상이 λ˜λŠ” 것 쀑, κ°€μž₯ 짧은 κ²ƒμ˜ 길이λ₯Ό κ΅¬ν•˜λŠ” ν”„λ‘œκ·Έλž¨μ„ μž‘μ„±ν•˜μ‹œμ˜€. μž…λ ₯ 첫째 쀄에 N (10 ≤ N < 100,000)κ³Ό S (0 < S ≤ 100,000,000)κ°€ μ£Όμ–΄μ§„λ‹€. λ‘˜μ§Έ μ€„μ—λŠ” μˆ˜μ—΄μ΄ μ£Όμ–΄μ§„λ‹€. μˆ˜μ—΄μ˜ 각 μ›μ†ŒλŠ” 곡백으둜 κ΅¬λΆ„λ˜μ–΄μ Έ 있으며, 10,000μ΄ν•˜μ˜ μžμ—°μˆ˜μ΄λ‹€. 좜λ ₯ 첫째 쀄에 κ΅¬ν•˜κ³ μž ν•˜λŠ” μ΅œμ†Œμ˜ κΈΈ

www.acmicpc.net

#include <iostream>
using namespace std;

int arr[100000];

int main()
{
	int N, S;
	cin >> N >> S;
	for (int i = 0; i < N; i++)
		cin >> arr[i];

	int ans = -1;
	long long sum = 0;
	int start = 0, end = 0;
	while (1) {
		if (sum >= S)
			sum -= arr[start++];
		else if (end == N)
			break;
		else
			sum += arr[end++];

		if (sum >= S && (ans == -1 || end - start < ans))
			ans = end - start;
	}
	if (ans == -1)
		cout << 0;
	else
		cout << ans;
}

 

https://leetcode.com/problems/container-with-most-water/

 

Container With Most Water - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

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

class Solution {
public:
    int maxArea(vector<int>& height) {
        int start = 0, end = height.size() - 1;
        int answer = (end - start) * min(height[start], height[end]);
        while (start < end) {
            if (height[start] <= height[end])
                start++;
            else
                end--;

            answer = max(answer, (end - start) * min(height[start], height[end]));
        }

        return answer;
    }
};

 

https://leetcode.com/problems/3sum/

 

3Sum - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

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

class Solution
{
public:
    vector<vector<int>> threeSum(vector<int> nums)
    {
        vector<vector<int>> answers;
        int target;

        sort(nums.begin(), nums.end());
        for (int i = 0; i < nums.size(); ++i)
        {
            if (target == -nums[i])
                continue;

            target = -nums[i];
            int left = i + 1, right = nums.size() - 1, sum = 0;
            while (left < right)
            {
                sum = nums[left] + nums[right];

                if (target > sum)
                    ++left;
                else if (target < sum)
                    --right;
                else
                {
                    vector<int> temp = {nums[left], -target, nums[right]};
                    answers.push_back(temp);

                    while (left < nums.size() && nums[left] == temp[0])
                        ++left;
                    while (right >= 0 && nums[right] == temp[2])
                        --right;
                }
            }
        }

        return answers;
    }
};

 

https://leetcode.com/problems/3sum-closest/

 

3Sum Closest - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

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

class Solution
{
public:
    int threeSumClosest(vector<int>& nums, int target)
    {
        int closest = 1e9, num1 = 1e9;

        sort(nums.begin(), nums.end());
        for (int i = 0; i < nums.size(); ++i)
        {
            if (num1 == nums[i])
                continue;

            num1 = nums[i];
            int num2 = i + 1, num3 = nums.size() - 1, sum = 0;
            while (num2 < num3)
            {
                sum = num1 + nums[num2] + nums[num3];

                int diff1 = abs(sum - target);
                int diff2 = abs(closest);
                closest = diff1 < diff2 ? sum - target : closest;

                if (sum < target)
                    ++num2;
                else if (sum > target)
                    --num3;
                else
                {
                    vector<int> temp = { nums[num2], nums[num3] };
                    while (num2 < nums.size() && nums[num2] == temp[0])
                        ++num2;
                    while (num3 >= 0 && nums[num3] == temp[1])
                        --num3;
                }
            }
        }

        return target + closest;
    }
};

 

μŠ¬λΌμ΄λ”© μœˆλ„μš°(Sliding Window)

투 ν¬μΈν„°μ²˜λŸΌ ꡬ간을 ν›‘μœΌλ©΄μ„œ μ§€λ‚˜κ°„λ‹€λŠ” 곡톡점이 μžˆμœΌλ‚˜ μ–΄λА μˆœκ°„μ—λ„ κ΅¬κ°„μ˜ 넓이가 λ™μΌν•˜λ‹€λŠ” 차이점이 μžˆλ‹€.

 

μŠ¬λΌμ΄λ”© μœˆλ„μš°

 

문제

 

https://programmers.co.kr/learn/courses/30/lessons/72414

 

μ½”λ”©ν…ŒμŠ€νŠΈ μ—°μŠ΅ - κ΄‘κ³  μ‚½μž…

μ‹œκ°„μ„ λ‚˜νƒ€λ‚΄λŠ” HH, H1, H2의 λ²”μœ„λŠ” 00~99, 뢄을 λ‚˜νƒ€λ‚΄λŠ” MM, M1, M2의 λ²”μœ„λŠ” 00~59, 초λ₯Ό λ‚˜νƒ€λ‚΄λŠ” SS, S1, S2의 λ²”μœ„λŠ” 00~59κΉŒμ§€ μ‚¬μš©λ©λ‹ˆλ‹€. 잘λͺ»λœ μ‹œκ°μ€ μž…λ ₯으둜 μ£Όμ–΄μ§€μ§€ μ•ŠμŠ΅λ‹ˆλ‹€. (예: 04:60:24, 11

programmers.co.kr

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

int StringToSec(string s)
{
	int time = stoi(s.substr(0, 2)) * 3600;
	time += stoi(s.substr(3, 2)) * 60;
	time += stoi(s.substr(6, 2));

	return time;
}

string SecToString(int i)
{
	string time = "";

	int s = i % 60;
	i /= 60;

	int m = i % 60;
	i /= 60;

	int h = i;

	if (h < 10)
		time += "0";
	time += to_string(h) + ":";

	if (m < 10)
		time += "0";
	time += to_string(m) + ":";

	if (s < 10)
		time += "0";
	time += to_string(s);

	return time;
}

int total_time[360000]{};

string solution(string play_time, string adv_time, vector<string> logs) {
	int play_time_sec = StringToSec(play_time);
	int adv_time_sec = StringToSec(adv_time);

	if (play_time_sec == adv_time_sec)
		return SecToString(0);

	for (int i = 0; i < logs.size(); ++i) {
		int start = StringToSec(logs[i].substr(0, 8));
		int end = StringToSec(logs[i].substr(9, 8));

		for (int i = start; i < end; i++)
			total_time[i]++;
	}

	int ans = 0, start = 0, end = adv_time_sec;
	long long sum = 0, max = 0;
	for (int i = start; i < end; i++)
		sum += total_time[i];
	max = sum;

	while (end <= play_time_sec) {
		int diff = -total_time[start++] + total_time[++end - 1];
		sum += (long long)diff;

		if (sum > max) {
			max = sum;
			ans = start;
		}
	}

	return SecToString(ans);
}

 

https://www.acmicpc.net/problem/2531

 

2531번: νšŒμ „ 초λ°₯

첫 번째 μ€„μ—λŠ” νšŒμ „ 초λ°₯ λ²¨νŠΈμ— 놓인 μ ‘μ‹œμ˜ 수 N, 초λ°₯의 κ°€μ§“μˆ˜ d, μ—°μ†ν•΄μ„œ λ¨ΉλŠ” μ ‘μ‹œμ˜ 수 k, 쿠폰 번호 cκ°€ 각각 ν•˜λ‚˜μ˜ 빈 칸을 사이에 두고 μ£Όμ–΄μ§„λ‹€. 단, 2 ≤ N ≤ 30,000, 2 ≤ d ≤ 3,000, 2 ≤

www.acmicpc.net

#include <iostream>
#include <deque>
#include <algorithm>
using namespace std;

int sushi[300001];
int sushi_kind[3001];

int main() 
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);

    int N, D, K, C;
    cin >> N >> D >> K >> C;
    for (int i = 0; i < N; i++)     
        cin >> sushi[i];

    int cnt = 0;
    int result = 0;

    // 1~K κΉŒμ§€μ˜ 초λ°₯을 덱에 λ„£κ³  μ’…λ₯˜λ₯Ό μ„Όλ‹€.
    deque<int> dq;
    for (int i = 0; i < K; i++) {
        dq.push_back(sushi[i]);
        if (!sushi_kind[sushi[i]]++)
            cnt++;
        result = max(result, cnt);
    }

    for (int i = 0; i < N - 1; i++) {
        // 맨 μ•ž μŠ€μ‹œλ₯Ό λΉΌκ³  ν•΄λ‹Ή μŠ€μ‹œμ˜ μ’…λ₯˜κ°€ 덱에 없을 경우 cntλ₯Ό λΊ€λ‹€.
        dq.pop_front();
        if (!(--sushi_kind[sushi[i]]))
            cnt--;

        // λ‹€μŒ μŠ€μ‹œλ₯Ό 덱에 λ„£κ³  μƒˆλ‘œμš΄ μ’…λ₯˜λΌλ©΄ cntλ₯Ό 더해쀀닀
        dq.push_back(sushi[(i + K) % N]);
        if (!(sushi_kind[sushi[(i + K) % N]])++)
            cnt++;

        result = max(result, cnt + (sushi_kind[C] == 0));
    }

    cout << result;
}

 

거뢁이와 토끼(Tortoise and Hare)

https://fierycoding.tistory.com/45

 

ν”Œλ‘œμ΄λ“œμ˜ 토끼와 거뢁이 μ•Œκ³ λ¦¬μ¦˜(Floyd's Tortoise & Hare Algorithm) / 증λͺ… / leetcode 287번 / 파이썬

λ°œλ‹¨ μ–΄λŠλ‚  λ‚˜μ˜ 유튜브 μ•Œκ³ λ¦¬μ¦˜μ— 뜬 JOMA... 사싀 μ˜ˆμ „μ—λ„ ν•œ 번 λ³Έ 적 μžˆλŠ” μ˜μƒμΈλ° κ·Έλ•ŒλŠ” 킬킬킬 웃고 λ„˜μ–΄κ°”μ§€λ§Œ μ΄μ œμ™€μ„œ λ‹€μ‹œ λ³΄λ‹ˆ μ•Œκ³ λ¦¬μ¦˜μ˜ λ‚΄μš©μ΄ κΆκΈˆν•΄μ‘ŒμŠ΅λ‹ˆλ‹€. κ²°κ΅­μ—” μ•Œμ•„λ³΄

fierycoding.tistory.com

 

문제

https://leetcode.com/problems/linked-list-cycle/description/

class Solution {
public:
    bool hasCycle(ListNode *head) {
        if(head == nullptr)
            return false;
        
        ListNode* fast = head;
        ListNode* slow = head;
        while(fast->next && fast->next->next)
        {
            fast = fast->next->next;
            slow = slow->next;

            if(fast == slow)
            return true;
        }
        return false;        
    }
};

 

https://leetcode.com/problems/reorder-list/description/

#include <stack>

class Solution {
public:
    void reorderList(ListNode* head) {
        ListNode* fast = head;
        ListNode* slow = head; // mid
        while (fast != nullptr && fast->next != nullptr) {
            slow = slow->next;
            fast = fast->next->next;
        }

        stack<ListNode*> st;
        while (slow != nullptr) {
            st.push(slow);
            slow = slow->next;
        }

        ListNode* node = head;
        while(!st.empty()) {
            ListNode* temp = st.top();
            st.pop();

            temp->next = node->next;
            node->next = temp;
            node = temp->next;
        }
        node->next = nullptr;
    }
};
μ €μž‘μžν‘œμ‹œ (μƒˆμ°½μ—΄λ¦Ό)
'πŸ“ Computer Science/✏ Algorithm' μΉ΄ν…Œκ³ λ¦¬μ˜ λ‹€λ₯Έ κΈ€
  • [C++] 트라이(Trie)
  • [C++] μœ λ‹ˆμ˜¨ νŒŒμΈλ“œ(Union-Find)
  • [C++] next_permutation, prev_permutation
  • [C++] λΉ„νŠΈ μ—°μ‚°μž
Blxxming
Blxxming
CS 지식과 κ³΅λΆ€ν•˜λ‹€ 배운 것, κ²½ν—˜ν•œ 것 등을 κΈ°λ‘ν•˜λŠ” λΈ”λ‘œκ·Έμž…λ‹ˆλ‹€.
  • Blxxming
    πŸ’‘λ²ˆλœ©πŸ’‘
    Blxxming
  • 전체
    였늘
    μ–΄μ œ
  • 곡지사항

    • Tech Interview
    • πŸ“š Tech (246)
      • πŸ“ Computer Science (96)
        • ✏ OS (12)
        • ✏ Network & Web (10)
        • ✏ Database (11)
        • ✏ Data Structure (6)
        • ✏ Algorithm (40)
        • ✏ Design Pattern (9)
        • ✏ Cloud Computing (3)
        • ✏ (5)
      • πŸ“ Language (73)
        • ✏ Language (6)
        • ✏ C & C++ (11)
        • ✏ C# (19)
        • ✏ JAVA (37)
      • πŸ“ Game (43)
        • ✏ Computer Graphics (2)
        • ✏ Unity (14)
        • ✏ Unreal (26)
        • ✏ (1)
      • πŸ“ Book (34)
        • ✏ Effective (3)
        • ✏ Game Server (16)
        • ✏ Clean Code (14)
        • ✏ (1)
  • hELLOΒ· Designed Byμ •μƒμš°.v4.10.0
Blxxming
[C++] 투 포인터(Two Pointer)
μƒλ‹¨μœΌλ‘œ

ν‹°μŠ€ν† λ¦¬νˆ΄λ°”