How to find pairs of neighboring and non-neighboring elements in an unordered array?
Example: 10 20 20 10 10 30 50 10 20 . The pairs here are 10-10 , 10-10 , 20-20 . That is only 3 pairs.
As I understand it, you first need to sort the array in order to search for neighboring elements by it. It takes only 4 \ 7 tests. What is the problem?
#include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { int n, count = 0; cin >> n; vector<int> c(n); for (int i = 0; i < n; i++) { cin >> c[i]; } sort(c.begin(), c.end()); for (int i = 0; i < n - 1; i++) { if (c[i] == c[i + 1]) { count++; } } if (count % 2 == 0) { count /= 2; } else if (count % 2 != 0) { count++; count /= 2; } cout << count; return 0; }
i++add to the loop wherecount++, and below the division can be removed - J. Doe