在 2n+1 个整数元素的数组中查找单个元素
给定一个包含 2n+1 个整数的数组,n 个元素在数组中的任意位置出现两次,而单个整数只在其中某处出现一次。使用 O(n) 操作和 O(1) 额外内存找到孤独的整数。
例子 :
Input : { 1, 1, 2, 2, 3, 3, 4, 4, 5}
Output : 5
Input : { 7, 9, 6, 8, 3, 7, 8, 6, 9}
Output : 3
这个想法是对所有元素进行异或。所有元素的 XOR 给了我们结果。这个想法基于以下 XOR 属性。
- 一个数与自身的异或是0。
- 一个数与 0 的 XOR 就是这个数。
C++
// CPP program to find only
// element in an array where
// every element appears twice.
#include
using namespace std;
// Find non repeating
// number in an array
int findNonRepeating(int arr[],
int n)
{
int res = 0;
for (int i = 0; i < n; i++)
res = res ^ arr[i];
return res;
}
// Driver Code
int main()
{
int arr[] = { 3, 8, 3, 2, 2, 1, 1 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << findNonRepeating(arr, n);
return 0;
}
Java
// Java program to find only element
// in an array where every element
// appears twice.
import java.io.*;
class GFG
{
// Find non repeating
// number in an array
static int findNonRepeating(int []arr,
int n)
{
int res = 0;
for (int i = 0; i < n; i++)
res = res ^ arr[i];
return res;
}
// Driver Code
static public void main (String[] args)
{
int []arr = {3, 8, 3, 2, 2, 1, 1};
int n = arr.length;
System.out.println(findNonRepeating(arr, n));
}
}
// This code is contributed by vt_m.
Python
# Find non repeating
# number in an array
def findNonRepeating(a, n):
res = 0
# XOR of all numbers
for i in range(n):
res ^= a[i]
return res
# Driver code
a = [ 3, 8, 3, 2, 2, 1, 1 ]
n = len(a)
print findNonRepeating(a, n)
# This code is contributed
# by 'Striver'.
C#
// C# program to find only element
// in an array where every element
// appears twice.
using System;
class GFG
{
// Find non repeating number in an array
static int findNonRepeating(int []arr,
int n)
{
int res = 0;
for (int i = 0; i < n; i++)
res = res ^ arr[i];
return res;
}
// Driver Code
static public void Main (String []args)
{
int []arr = {3, 8, 3, 2, 2, 1, 1};
int n = arr.Length;
Console.WriteLine(findNonRepeating(arr,
n));
}
}
// This code is contributed by vt_m.
PHP
Javascript
输出 :
8