반응형
다시 푸는 문제 !
마찬가지로 투포인터를 이용해 풀이할 수 있었다.
#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int cmp(pair<int, int> a, pair<int, int> b) {
int aLen = a.second - a.first;
int bLen = b.second - b.first;
if(bLen == aLen)
return a.first < b.first;
else
return aLen < bLen;
}
vector<int> solution(vector<int> sequence, int k) {
vector<pair<int, int>> answer;
int result = 0;
int j = 0;
for(int i = 0; i < sequence.size(); i++) {
while(result < k && j < sequence.size()) {
result += sequence[j];
j++;
}
if(result == k) {
answer.push_back({i, j - 1});
}
result -= sequence[i];
}
sort(answer.begin(), answer.end(), cmp);
return {answer[0].first, answer[0].second};
}
다시 풀었다.
투포인터는 풀 때마다 어렵다 ㅎㅎ
투포인터는 두 가지 접근 방법이 있는데
1. 오른쪽이 될떄까지 가보고 왼쪽이 하나씩 당겨지는 방식
#include <string>
#include <vector>
#include <queue>
#include <iostream>
using namespace std;
// 길이, 시작인덱스, 마지막인덱스로 정렬
struct PQ {
int len;
int start;
int end;
bool operator<(const PQ& other) const {
if(len != other.len) return len > other.len;
if(start != other.start) return start > other.start;
if(end != other.end) return end > other.end;
}
};
priority_queue<PQ, vector<PQ>> pq;
vector<int> solution(vector<int> sequence, int k) {
vector<int> answer;
int j = -1;
int totalValue = 0;
for(int i = 0; i < sequence.size(); i++) {
while(totalValue < k && j + 1 < sequence.size()) {
totalValue += sequence[++j];
}
if(totalValue == k) {
pq.push({j - i, i, j});
}
totalValue -= sequence[i];
}
return {pq.top().start, pq.top().end};
}
2. 오른쪽이 하나씩 가지고 왼쪽이 될떄까지 당겨지는 방식
#include <string>
#include <vector>
#include <queue>
#include <iostream>
using namespace std;
// 길이, 시작인덱스, 마지막인덱스로 정렬
struct PQ {
int len;
int start;
int end;
bool operator<(const PQ& other) const {
if(len != other.len) return len > other.len;
if(start != other.start) return start > other.start;
if(end != other.end) return end > other.end;
}
};
priority_queue<PQ, vector<PQ>> pq;
vector<int> solution(vector<int> sequence, int k) {
vector<int> answer;
int start = 0;
int totalValue = 0;
for(int end = 0; end < sequence.size(); end++) {
totalValue += sequence[end];
while(totalValue > k && start < sequence.size()) {
totalValue -= sequence[start++];
}
if(totalValue == k) {
pq.push({end - start, start, end});
}
}
return {pq.top().start, pq.top().end};
}
이렇게 두 가지 방법이 있다. 후자가 더 쉬운듯??
반응형
'[알고리즘 + 자료구조] > [프로그래머스]' 카테고리의 다른 글
[프로그래머스] 미로 탈출 C++ (0) | 2024.03.22 |
---|---|
[프로그래머스] 등산코스 정하기 (0) | 2024.03.22 |
[프로그래머스] 연속 부분 수열 합의 개수 (0) | 2024.03.19 |
프로그래머스 거리두기 확인하기 (0) | 2023.10.09 |
프로그래머스 후보키 C++ (1) | 2023.10.05 |