给定两个数组A []和B [] 。第二个数组B []包含A []的所有元素,除了1个额外的元素。任务是找到那个额外的元素。
例子:
Input: A[] = { 1, 2, 3 }, B[] = {1, 2, 3, 4}
Output: 4
Element 4 is not present in array
Input: A[] = {10, 15, 5}, B[] = {10, 100, 15, 5}
Output: 100
简单方法:运行嵌套循环,并找到B中的元素[],这是不存在于A []。这种方法的时间复杂度将是O(n 2 ) 。
有效的方法:如果A []和B []进行异或在一起,然后A []中的每个元素将给予0与其在B []发生和额外的元件比如X当异或与0会给的所有元素(X XOR 0)= X ,这就是结果。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to return the extra
// element in B[]
int extraElement(int A[], int B[], int n)
{
// To store the result
int ans = 0;
// Find the XOR of all the element
// of array A[] and array B[]
for (int i = 0; i < n; i++)
ans ^= A[i];
for (int i = 0; i < n + 1; i++)
ans ^= B[i];
return ans;
}
// Driver code
int main()
{
int A[] = { 10, 15, 5 };
int B[] = { 10, 100, 15, 5 };
int n = sizeof(A) / sizeof(int);
cout << extraElement(A, B, n);
return 0;
}
Java
// Java implementation of the approach
class GFG
{
// Function to return the extra
// element in B[]
static int extraElement(int A[], int B[], int n)
{
// To store the result
int ans = 0;
// Find the XOR of all the element
// of array A[] and array B[]
for (int i = 0; i < n; i++)
ans ^= A[i];
for (int i = 0; i < n + 1; i++)
ans ^= B[i];
return ans;
}
// Driver code
public static void main (String[] args)
{
int A[] = { 10, 15, 5 };
int B[] = { 10, 100, 15, 5 };
int n = A.length;
System.out.println(extraElement(A, B, n));
}
}
// This code is contributed by kanugargng
Python3
# Python3 implementation of the approach
# Function to return the extra
# element in B[]
def extraElement(A, B, n):
# To store the result
ans = 0;
# Find the XOR of all the element
# of array A[] and array B[]
for i in range(n):
ans ^= A[i];
for i in range(n + 1):
ans ^= B[i];
return ans;
# Driver code
A = [ 10, 15, 5 ];
B = [ 10, 100, 15, 5 ];
n = len(A);
print(extraElement(A, B, n));
# This code is contributed by 29AjayKumar
C#
// C# implementation of the approach
using System;
class GFG
{
// Function to return the extra
// element in B[]
static int extraElement(int []A,
int []B, int n)
{
// To store the result
int ans = 0;
// Find the XOR of all the element
// of array A[] and array B[]
for (int i = 0; i < n; i++)
ans ^= A[i];
for (int i = 0; i < n + 1; i++)
ans ^= B[i];
return ans;
}
// Driver code
public static void Main (String[] args)
{
int []A = { 10, 15, 5 };
int []B = { 10, 100, 15, 5 };
int n = A.Length;
Console.WriteLine(extraElement(A, B, n));
}
}
// This code is contributed by 29AjayKumar
Javascript
输出:
100
时间复杂度: O(N)
空间复杂度: O(1)
如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。