本文概述
- C#
- C#
例子 :
Input : arr = {1, 2, 3, 2, 3, 1, 3}
Output : 3Input : arr = {5, 7, 2, 7, 5, 2, 5}
Output : 5
C#
//C# program to find the element
//occurring odd number of times
using System;
class GFG {
//Function to find the element
//occurring odd number of times
static int getOddOccurrence( int [] arr, int arr_size)
{
for ( int i = 0;
i <
arr_size;
i++) {
int count = 0;
for ( int j = 0;
j <
arr_size;
j++) {
if (arr[i] == arr[j])
count++;
}
if (count % 2 != 0)
return arr[i];
}
return -1;
}//Driver code
public static void Main()
{
int [] arr = { 2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2 };
int n = arr.Length;
Console.Write(getOddOccurrence(arr, n));
}
}//This code is contributed by Sam007
【C#程序查找出现的奇数次】输出如下:
5
一种更好的解决方案是使用哈希。使用数组元素作为键, 并将其计数作为值。创建一个空的哈希表。一对一遍历给定的数组元素并存储计数。该解决方案的时间复杂度为O(n)。但是它需要额外的空间来进行哈希处理。
程序:
C#
//C# program to find the element
//occurring odd number of times
using System;
class GFG {
//Function to find the element
//occurring odd number of times
static int getOddOccurrence( int [] arr, int arr_size)
{
int res = 0;
for ( int i = 0;
i <
arr_size;
i++) {
res = res ^ arr[i];
}
return res;
}//Driver code
public static void Main()
{
int [] arr = { 2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2 };
int n = arr.Length;
Console.Write(getOddOccurrence(arr, n));
}
}//This code is contributed by Sam007
输出如下:
5
请参考完整的文章查找出现次数的奇数更多细节!
推荐阅读
- C#谓词委托用法介绍
- 用于最大总和连续子数组的C#程序
- C#编程语言入门学习指南提纲
- 不能加硬盘?C盘不够存储卡凑!
- 电脑主板怎样刷bios?
- android studio快捷键大全
- svchost一直在下载怎样处理
- 笔记本触摸板关不掉怎样处理
- 大片不流畅?插帧60fps看电影更畅快!