jasonpogi1669

Determine the number with odd frequency using sort in C++

Nov 4th, 2021 (edited)
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.60 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. int main() {
  6.     int n;
  7.     cin >> n;
  8.     vector<int> a(n);
  9.     for (int i = 0; i < n; i++) {
  10.         cin >> a[i];
  11.     }
  12.     int res = -1;
  13.     int i = 0;
  14.     int j = 0;
  15.     // create two pointersL i and j
  16.     // i = start pointer of the element
  17.     // j = moving pointer of the element
  18.     // once j reaches the last occurrence of the element,
  19.     // get the difference between j and i (frequency)
  20.     for (i = 0; i < (int) a.size(); i = j) {
  21.         while (j < (int) a.size() && a[i] == a[j]) {
  22.             j++;
  23.         }
  24.         if ((j - i) & 1) {
  25.             res = a[i];
  26.         }
  27.     }
  28.     cout << res << '\n';
  29.     return 0;
  30. }
  31.  
Add Comment
Please, Sign In to add comment