C/C++ 程序用于查找给定正整数数组中出现奇数次的数字。此数组中所有数字都出现偶数次。
此 C++ 程序用于在给定的正整数数组中查找出现奇数次的数字。此数组中所有数字都出现偶数次。
Input: arr[] = {5, 7, 8, 8, 5, 8, 8, 7, 7}
Output: 7说明
使用两个循环,其中外循环逐个遍历所有元素,内循环统计外循环遍历的元素出现的次数。
示例
#include <iostream>
using namespace std;
int Odd(int arr[], int n){
for (int i = 0; i < n; i++) {
int ctr = 0;
for (int j = 0; j < n; j++) {
if (arr[i] == arr[j])
ctr++;
}
if (ctr % 2 != 0)
return arr[i];
}
return -1;
}
int main() {
int arr[] = {5, 7, 8, 8, 5, 8, 8, 7, 7};
int n = 9;
cout <<Odd(arr, n);
return 0;
}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP