Let’s say, we want to extract the unique elements (numbers) in a given array (vector, list) and return them in sorted order. For example,
The array is [1, 1, 0, 0, 2], and the output is [0, 1, 2].
You can write a method in a straightforward method with two steps – extract unique numbers and then sort them.
template <class T>
vector<T> uniqueAndSorted(const vector<T> &arr) {
unordered_set<T> data;
vector<T> ans;
for (const auto &n: arr) {
if (data.count(n)) continue;
data.insert(n);
ans.push_back(n);
}
sort(begin(ans), end(ans));
return ans;
}
You can, implement this with the following two liner – which makes use of the set (which maintains the key in sorted order). First, we construct the set based on the given array – which will give us a set that contains unique elements. Then we just need to construct the returned vector/array and the items will be automatically in sorted order as the set maintains the keys in ascending order.
template <class T>
vector<T> uniqueAndSorted(const vector<T> &arr) {
set<int> ans(begin(arr), end(arr));
return vector<T>(begin(ans), end(ans));
}
–EOF (The Ultimate Computing & Technology Blog) —
276 wordsLast Post: Greedy Algorithm to Find Valid Matrix Given Row and Column Sums
Next Post: O(NLogN) to Compute the Median in a Stream using Two Priority Queues