C++程序:查找数组中左右两侧奇偶数数量相同的索引?
查找左右两侧奇偶数数量相同的数组索引,是指在数组中找到一个元素,其左右两侧的奇数或偶数数量相等,即左侧的数字数量 = 右侧的数字数量。
这里,我们需要一些与概念相关的定义:
数组 - 一个存储相同数据类型元素的容器。
数组索引 - 元素的位置称为其索引。数组的索引始终从 0 开始。
偶数 - 能被 2 整除的数。
奇数 - 不能被 2 整除的数。
一个整数可以是偶数或奇数。
现在,让我们看一个例子,使概念更清晰。
Input: arr[] = {4, 3, 2, 1, 2}
Output : 2解释
在索引 2 处,其左侧有一个奇数,右侧有一个奇数。
我们有一个包含 n 个整数的数组,需要找到数组元素的索引,使得其左侧有偶数个元素,右侧也有偶数个元素,或者需要找到其左侧奇数元素的频率等于其右侧奇数元素的频率。如果没有这样的条件,则需要输出 -1;如果有这样的条件,则需要输出其索引。
算法
要计算左右两侧奇偶数数量相同的元素的索引,我们需要找到给定元素左侧和右侧的元素数量。
给定数组 arr[],数组元素数量为 n。
Step 1 : For i -> 0 to n, follow step 2 - 5: Step 2: initialise e_l, o_l, e_r, o_r to 0. Step 3: for j -> o to i Step 3.1 : count values for e_l and o_l. Step 4: for j -> i+1 to n Step 4.1 : count values for e_r and o_r. Step 5: if(e_l == e_r) or (o_l == e_r ) , print i.
示例
#include <iostream>
using namespace std;
int main() {
int arr[] = {4, 3, 2, 1, 2};
int n = 5;
cout<<"The array is : ";
for(int i = 0; i < n; i++) {
cout<<arr[i]<<" ";
}
cout<<"\nThe index of the element with the same count of even or odd numbers on both sides = ";
for (int i = 0; i < n; i++) {
int o_l = 0, e_l = 0;
int o_r = 0, e_r = 0;
for (int j = 0; j < i; j++) {
if (arr[j] % 2 == 0)
e_l++;
else
o_l++;
}
for (int k = n - 1; k > i; k--) {
if (arr[k] % 2 == 0)
e_r++;
else
o_r++;
}
if (e_r == e_l || o_r == o_l)
cout<<i<<endl;
}
return 0;
}输出
The array is : 4 3 2 1 2 The index of the element with the same count of even or odd numbers on both sides = 2
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP