알고리즘과 언어/c++
최대값, 최소값 max_element min_element (프로그래머스 프린터)
nextcoder
2021. 8. 19. 18:17
queue는 기본적으로 순회가 불가능하기에 최대값을 구할 수 없는 줄 알고 queue를 사용하지 않고 풀었지만
*max_element(Queue.begin(), Queue.end()) 와 같이 O(n)으로 최대값을 구할 수 있다. (이터레이터를 반환하기에 * 필요)
https://en.cppreference.com/w/cpp/algorithm/max_element
std::max_element - cppreference.com
(1) template< class ForwardIt > ForwardIt max_element( ForwardIt first, ForwardIt last ); (until C++17) template< class ForwardIt > constexpr ForwardIt max_element( ForwardIt first, ForwardIt last ); (since C++17) template< class ExecutionPolicy, class For
en.cppreference.com
queue를 사용하지 않은 코드)
#include <string>
#include <vector>
using namespace std;
int solution(vector<int> priorities, int location) {
int answer = 1;
int max;
int now = 0;
int check[100] = {0, };
while(1)
{
max = -1;
for(int i = 0; i < priorities.size(); i++) //find max
{
if(check[i] == 0 && priorities[i] > max)
{
max = priorities[i];
}
}
for(int i= now; i< priorities.size() + now; i++) //now부터 순회하며 max값 찾기
{
if(check[(i % priorities.size())] == 0 && priorities[(i % priorities.size())] == max)
{
now = i % priorities.size();
check[now] = 1; //check
break;
}
}
if(now == location)
break;
answer++;
}
return answer;
}