
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Closest Value for Every Element in Array in C++
Here we will see how to find the closest value for every element in an array. If an element x has next element that is larger than it, and also present in the array, then that will be the greater value of that element. If the element is not present, then return -1. Suppose the array elements are [10, 5, 11, 6, 20, 12], then the greater elements are [11, 6, 12, 10, -1, 20]. As 20 has not greater value in the array, then print -1.
To solve this, we will use the set in C++ STL. The set is implemented using the binary tree approach. In binary tree always the inorder successor is the next larger element. So we can get the element in O(log n) time.
Example
#include<iostream> #include<set> using namespace std; void nearestGreatest(int arr[], int n) { set<int> tempSet; for (int i = 0; i < n; i++) tempSet.insert(arr[i]); for (int i = 0; i < n; i++) { auto next_greater = tempSet.upper_bound(arr[i]); if (next_greater == tempSet.end()) cout << -1 << " "; else cout << *next_greater << " "; } } int main() { int arr[] = {10, 5, 11, 6, 20, 12}; int n = sizeof(arr) / sizeof(arr[0]); nearestGreatest(arr, n); }
Output
11 6 12 10 -1 20
Advertisements