반응형
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
Tags
- Kafka
- upper_bound
- 처우협의
- incr
- 오퍼레터
- 경력
- Docker
- 기술면접
- 백트래킹
- @P0
- 백준
- 퇴사통보
- 소프티어
- BOJ
- BFS
- 매개변수탐색
- boj #19237 #어른 상어
- OFFSET
- 6987
- dfs
- msSQL
- 이분탐색
- compose
- 물채우기
- 성적평가
- softeer
- 파라메트릭
- 13908
- 연결요소
- 처우산정
Archives
- Today
- Total
기술 블로그
Next Greater Element(NGE) 본문
728x90
반응형
https://www.geeksforgeeks.org/next-greater-element/
https://stackoverflow.com/questions/44417069/next-greater-element-in-array
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | // A Stack based C++ program to find next // greater element for all array elements. #include <bits/stdc++.h> using namespace std; /* prints element and NGE pair for all elements of arr[] of size n */ void printNGE(int arr[], int n) { stack < int > s; /* push the first element to stack */ s.push(arr[0]); // iterate for rest of the elements for (int i = 1; i < n; i++) { if (s.empty()) { s.push(arr[i]); continue; } /* if stack is not empty, then pop an element from stack. If the popped element is smaller than next, then a) print the pair b) keep popping while elements are smaller and stack is not empty */ while (s.empty() == false && s.top() < arr[i]) { cout << s.top() << " --> " << arr[i] << endl; s.pop(); } /* push next to stack so that we can find next greater for it */ s.push(arr[i]); } /* After iterating over the loop, the remaining elements in stack do not have the next greater element, so print -1 for them */ while (s.empty() == false) { cout << s.top() << " --> " << -1 << endl; s.pop(); } } /* Driver program to test above functions */ int main() { int arr[] = {11, 13, 21, 3}; int n = sizeof(arr) / sizeof(arr[0]); printNGE(arr, n); return 0; } | cs |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | #include<iostream> #include <stack> using namespace std; void printNextGreaterElement(int input[], int inputSize) { stack<int> s; s.push(input[0]); for (int i = 1; i < inputSize; i++) { while (!s.empty() && s.top() < input[i]) { cout<<"Next greater element for "<<s.top()<<"\t = "<<input[i]<<"\n"; s.pop(); } s.push(input[i]); } while (!s.empty()) { int top = (int) s.top(); s.pop(); cout<<"Next greater element for "<<top<<"\t = null\n"; } } int main() { int input[] = { 98, 23, 54, 12, 20, 7, 27 }; printNextGreaterElement(input, 7); return 0; } | cs |
728x90
반응형
'알고리즘' 카테고리의 다른 글
다익스트라(Dijkstra) (0) | 2019.08.17 |
---|---|
세그먼트 트리(Segment Tree) (0) | 2019.07.29 |
2차원 배열을 함수 인자로 전달(포인터) (0) | 2019.07.01 |
SPFA (Shortest Path Faster Algorithm) (0) | 2019.06.01 |
MCMF(Minimum Cost Maximum Flow) (0) | 2019.05.23 |