C++中数组索引:左右两侧奇偶数计数相同
这里我们将看到一个问题,假设给定一个数组,包含n个元素。我们需要找到一个索引,使得其左侧偶数的频率与右侧偶数的频率相同,或者其左侧奇数的频率与右侧奇数的频率相同。如果没有这样的结果,则返回-1。
假设数组为{4, 3, 2, 1, 2, 4}。输出为2。索引2处的元素为2,其左侧只有一个奇数,右侧也只有一个奇数。
为了解决这个问题,我们将创建两个pair类型的向量来存储左右两侧的信息。左侧的向量将存储其左侧奇数和偶数的频率,右侧的向量将对右侧做同样的操作。如果左侧和右侧的偶数计数相同,或者左侧和右侧的奇数计数相同,则返回该索引。
算法
getIndex(arr, n) −
Begin define odd and even, and initialize as 0 define left_vector, right_vector for odd even pairs add (odd, even) into left_vector for i in range 0 to n-1, do if arr[i] is even, then increase even, otherwise increase odd add (odd, even) into left_vector done odd := 0 and even := 0 add (odd, even) into right_vector for i in range n-1 down to 1, do if arr[i] is even, then increase even, otherwise increase odd add (odd, even) into right_vector done reverse the right_vector for each element at index i in left_vector, do if left_vector[i].first = right_vector[i].first, or left_vector[i].odd= right_vector[i].odd, then return i done return -1 End
示例
#include <iostream> #include <vector> #include <utility> #include <algorithm> using namespace std; int getIndex(int n, int arr[]) { int odd = 0, even = 0; vector<pair<int, int >> left_vector, right_vector; left_vector.push_back(make_pair(odd, even)); for (int i = 0; i < n - 1; i++) { //count and store odd and even frequency for left side if (arr[i] % 2 == 0) even++; else odd++; left_vector.push_back(make_pair(odd, even)); } odd = 0, even = 0; right_vector.push_back(make_pair(odd, even)); //count and store odd and even frequency for right side for (int i = n - 1; i > 0; i--) { if (arr[i] % 2 == 0) even++; else odd++; right_vector.push_back(make_pair(odd, even)); } reverse(right_vector.begin(), right_vector.end()); for (int i = 0; i < left_vector.size(); i++) { if (left_vector[i].first == right_vector[i].first || left_vector[i].second == right_vector[i].second) return i; } return -1; } int main() { int arr[] = {4, 3, 2, 1, 2}; int n = sizeof(arr) / sizeof(arr[0]); int index = getIndex(n, arr); if(index == -1) { cout << "-1"; } else { cout << "index : " << index; } }
输出
index : 2
广告