fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int KthSmallest(vector<int>& arr, int k) {
  5. sort(arr.begin(), arr.end());
  6.  
  7. int uniqueCount = 0;
  8. int lastUnique = INT_MIN;
  9.  
  10. for (int i = 0; i < arr.size(); ++i) {
  11. if (arr[i] != lastUnique) {
  12. uniqueCount++;
  13. lastUnique = arr[i];
  14. }
  15. if (uniqueCount == k) {
  16. return arr[i];
  17. }
  18. }
  19. return -1;
  20. }
  21.  
  22.  
  23. int main() {
  24.  
  25. vector<int> arr = {10, 20, 7, 8, 7, 7, 6} ;
  26. int ans = KthSmallest(arr, 3);
  27. cout<<ans<<endl;
  28.  
  29. return 0;
  30. }
Success #stdin #stdout 0.01s 5288KB
stdin
Standard input is empty
stdout
8