给定一个由不同的正整数组成的数组和一个数字 x,找出数组中 XOR 等于 x 的整数对的数量。
例子:
Input : arr[] = {5, 4, 10, 15, 7, 6}, x = 5
Output : 1
Explanation : (10 ^ 15) = 5
Input : arr[] = {3, 6, 8, 10, 15, 50}, x = 5
Output : 2
Explanation : (3 ^ 6) = 5 and (10 ^ 15) = 5
一个简单的解决方案是遍历每个元素并检查是否有另一个数字与它的异或等于 x。该解决方案需要 O(n 2 ) 时间。这个问题的有效解决方案需要 O(n) 时间。这个想法是基于这样一个事实,即 arr[i] ^ arr[j] 等于 x 当且仅当 arr[i] ^ x 等于 arr[j]。
1) Initialize result as 0.
2) Create an empty hash set "s".
3) Do following for each element arr[i] in arr[]
(a) If x ^ arr[i] is in "s", then increment result by 1.
(b) Insert arr[i] into the hash set "s".
3) return result.
C++
// C++ program to Count all pair with given XOR
// value x
#include
using namespace std;
// Returns count of pairs in arr[0..n-1] with XOR
// value equals to x.
int xorPairCount(int arr[], int n, int x)
{
int result = 0; // Initialize result
// create empty set that stores the visiting
// element of array.
// Refer below post for details of unordered_set
// https://www.geeksforgeeks.org/unorderd_set-stl-uses/
unordered_set s;
for (int i=0; iJava
// Java program to Count all pair with
// given XOR value x
import java.util.*;
class GFG
{
// Returns count of pairs in arr[0..n-1] with XOR
// value equals to x.
static int xorPairCount(int arr[], int n, int x)
{
int result = 0; // Initialize result
// create empty set that stores the visiting
// element of array.
// Refer below post for details of unordered_set
// https://www.geeksforgeeks.org/unorderd_set-stl-uses/
HashSet s = new HashSet();
for (int i = 0; i < n; i++)
{
// If there exist an element in set s
// with XOR equals to x^arr[i], that means
// there exist an element such that the
// XOR of element with arr[i] is equal to
// x, then increment count.
if (s.contains(x ^ arr[i]) &&
(x ^ arr[i]) == (int) s.toArray()[s.size() - 1])
{
result++;
}
// Make element visited
s.add(arr[i]);
}
// return total count of
// pairs with XOR equal to x
return result;
}
// Driver code
public static void main(String[] args)
{
int arr[] = {5, 4, 10, 15, 7, 6};
int n = arr.length;
int x = 5;
System.out.print("Count of pairs with given XOR = "
+ xorPairCount(arr, n, x));
}
}
// This code contributed by Rajput-Ji
Python3
# Python3 program to count all the pair
# with given xor
# Returns count of pairs in arr[0..n-1]
# with XOR value equals to x.
def xorPairCount(arr, n, x):
result = 0 # Initialize result
# create empty set that stores the
# visiting element of array.
s = set()
for i in range(0, n):
# If there exist an element in set s
# with XOR equals to x^arr[i], that
# means there exist an element such
# that the XOR of element with arr[i]
# is equal to x, then increment count.
if(x ^ arr[i] in s):
result = result + 1
# Make element visited
s.add(arr[i])
return result
# Driver Code
if __name__ == "__main__":
arr = [5, 4, 10, 15, 7, 6]
n = len(arr)
x = 5
print("Count of pair with given XOR = " +
str(xorPairCount(arr, n, x)))
# This code is contributed by Anubhav Natani
C#
// C# program to Count all pair with
// given XOR value x
using System;
using System.Collections.Generic;
class GFG
{
// Returns count of pairs in arr[0..n-1] with XOR
// value equals to x.
static int xorPairCount(int []arr, int n, int x)
{
int result = 0; // Initialize result
// create empty set that stores the visiting
// element of array.
// Refer below post for details of unordered_set
// https://www.geeksforgeeks.org/unorderd_set-stl-uses/
HashSet s = new HashSet();
for (int i = 0; i < n; i++)
{
// If there exist an element in set s
// with XOR equals to x^arr[i], that means
// there exist an element such that the
// XOR of element with arr[i] is equal to
// x, then increment count.
if (s.Contains(x ^ arr[i]))
{
result++;
}
// Make element visited
s.Add(arr[i]);
}
// return total count of
// pairs with XOR equal to x
return result;
}
// Driver code
public static void Main()
{
int []arr = {5, 4, 10, 15, 7, 6};
int n = arr.Length;
int x = 5;
Console.WriteLine("Count of pairs with given XOR = "
+ xorPairCount(arr, n, x));
}
}
/* This code contributed by PrinciRaj1992 */
Javascript
C++
// C++ program to Count all pair with given XOR
// value x
#include
using namespace std;
// Returns count of pairs in arr[0..n-1] with XOR
// value equals to x.
int xorPairCount(int arr[], int n, int x)
{
int result = 0; // Initialize result
// create empty map that stores counts of
// individual elements of array.
unordered_map m;
for (int i=0; iJava
// Java program to Count all pair with given XOR
// value x
import java.util.*;
class GFG
{
// Returns count of pairs in arr[0..n-1] with XOR
// value equals to x.
static int xorPairCount(int arr[], int n, int x)
{
int result = 0; // Initialize result
// create empty map that stores counts of
// individual elements of array.
Map m = new HashMap<>();
for (int i = 0; i < n ; i++)
{
int curr_xor = x^arr[i];
// If there exist an element in map m
// with XOR equals to x^arr[i], that means
// there exist an element such that the
// XOR of element with arr[i] is equal to
// x, then increment count.
if (m.containsKey(curr_xor))
result += m.get(curr_xor);
// Increment count of current element
if(m.containsKey(arr[i]))
{
m.put(arr[i], m.get(arr[i]) + 1);
}
else{
m.put(arr[i], 1);
}
}
// return total count of pairs with XOR equal to x
return result;
}
// Driver code
public static void main(String[] args)
{
int arr[] = {2, 5, 2};
int n = arr.length;
int x = 0;
System.out.println("Count of pairs with given XOR = "
+ xorPairCount(arr, n, x));
}
}
// This code has been contributed by 29AjayKumar
Python3
# Python3 program to Count all pair with
# given XOR value x
# Returns count of pairs in arr[0..n-1]
# with XOR value equals to x.
def xorPairCount(arr, n, x):
result = 0 # Initialize result
# create empty map that stores counts
# of individual elements of array.
m = dict()
for i in range(n):
curr_xor = x ^ arr[i]
# If there exist an element in map m
# with XOR equals to x^arr[i], that
# means there exist an element such that
# the XOR of element with arr[i] is equal
# to x, then increment count.
if (curr_xor in m.keys()):
result += m[curr_xor]
# Increment count of current element
if arr[i] in m.keys():
m[arr[i]] += 1
else:
m[arr[i]] = 1
# return total count of pairs
# with XOR equal to x
return result
# Driver Code
arr = [2, 5, 2]
n = len(arr)
x = 0
print("Count of pairs with given XOR = ",
xorPairCount(arr, n, x))
# This code is contributed by Mohit Kumar
C#
// C# program to Count all pair with given XOR
// value x
using System;
using System.Collections.Generic;
class GFG
{
// Returns count of pairs in arr[0..n-1] with XOR
// value equals to x.
static int xorPairCount(int []arr, int n, int x)
{
int result = 0; // Initialize result
// create empty map that stores counts of
// individual elements of array.
Dictionary m = new Dictionary();
for (int i = 0; i < n ; i++)
{
int curr_xor = x^arr[i];
// If there exist an element in map m
// with XOR equals to x^arr[i], that means
// there exist an element such that the
// XOR of element with arr[i] is equal to
// x, then increment count.
if (m.ContainsKey(curr_xor))
result += m[curr_xor];
// Increment count of current element
if(m.ContainsKey(arr[i]))
{
var val = m[arr[i]];
m.Remove(arr[i]);
m.Add(arr[i], val + 1);
}
else
{
m.Add(arr[i], 1);
}
}
// return total count of pairs with XOR equal to x
return result;
}
// Driver code
public static void Main(String[] args)
{
int []arr = {2, 5, 2};
int n = arr.Length;
int x = 0;
Console.WriteLine("Count of pairs with given XOR = "
+ xorPairCount(arr, n, x));
}
}
// This code has been contributed by 29AjayKumar
Javascript
输出:
Count of pairs with given XOR = 1
时间复杂度: O(n)
如何处理重复?
如果输入数组中有重复项,上述有效解决方案将不起作用。例如,上述解决方案对 {2, 2, 5} 和 {5, 2, 2} 产生不同的结果。为了处理重复,我们存储所有元素的出现次数。我们使用 unordered_map 而不是 unordered_set。
C++
// C++ program to Count all pair with given XOR
// value x
#include
using namespace std;
// Returns count of pairs in arr[0..n-1] with XOR
// value equals to x.
int xorPairCount(int arr[], int n, int x)
{
int result = 0; // Initialize result
// create empty map that stores counts of
// individual elements of array.
unordered_map m;
for (int i=0; iJava
// Java program to Count all pair with given XOR
// value x
import java.util.*;
class GFG
{
// Returns count of pairs in arr[0..n-1] with XOR
// value equals to x.
static int xorPairCount(int arr[], int n, int x)
{
int result = 0; // Initialize result
// create empty map that stores counts of
// individual elements of array.
Map m = new HashMap<>();
for (int i = 0; i < n ; i++)
{
int curr_xor = x^arr[i];
// If there exist an element in map m
// with XOR equals to x^arr[i], that means
// there exist an element such that the
// XOR of element with arr[i] is equal to
// x, then increment count.
if (m.containsKey(curr_xor))
result += m.get(curr_xor);
// Increment count of current element
if(m.containsKey(arr[i]))
{
m.put(arr[i], m.get(arr[i]) + 1);
}
else{
m.put(arr[i], 1);
}
}
// return total count of pairs with XOR equal to x
return result;
}
// Driver code
public static void main(String[] args)
{
int arr[] = {2, 5, 2};
int n = arr.length;
int x = 0;
System.out.println("Count of pairs with given XOR = "
+ xorPairCount(arr, n, x));
}
}
// This code has been contributed by 29AjayKumar
蟒蛇3
# Python3 program to Count all pair with
# given XOR value x
# Returns count of pairs in arr[0..n-1]
# with XOR value equals to x.
def xorPairCount(arr, n, x):
result = 0 # Initialize result
# create empty map that stores counts
# of individual elements of array.
m = dict()
for i in range(n):
curr_xor = x ^ arr[i]
# If there exist an element in map m
# with XOR equals to x^arr[i], that
# means there exist an element such that
# the XOR of element with arr[i] is equal
# to x, then increment count.
if (curr_xor in m.keys()):
result += m[curr_xor]
# Increment count of current element
if arr[i] in m.keys():
m[arr[i]] += 1
else:
m[arr[i]] = 1
# return total count of pairs
# with XOR equal to x
return result
# Driver Code
arr = [2, 5, 2]
n = len(arr)
x = 0
print("Count of pairs with given XOR = ",
xorPairCount(arr, n, x))
# This code is contributed by Mohit Kumar
C#
// C# program to Count all pair with given XOR
// value x
using System;
using System.Collections.Generic;
class GFG
{
// Returns count of pairs in arr[0..n-1] with XOR
// value equals to x.
static int xorPairCount(int []arr, int n, int x)
{
int result = 0; // Initialize result
// create empty map that stores counts of
// individual elements of array.
Dictionary m = new Dictionary();
for (int i = 0; i < n ; i++)
{
int curr_xor = x^arr[i];
// If there exist an element in map m
// with XOR equals to x^arr[i], that means
// there exist an element such that the
// XOR of element with arr[i] is equal to
// x, then increment count.
if (m.ContainsKey(curr_xor))
result += m[curr_xor];
// Increment count of current element
if(m.ContainsKey(arr[i]))
{
var val = m[arr[i]];
m.Remove(arr[i]);
m.Add(arr[i], val + 1);
}
else
{
m.Add(arr[i], 1);
}
}
// return total count of pairs with XOR equal to x
return result;
}
// Driver code
public static void Main(String[] args)
{
int []arr = {2, 5, 2};
int n = arr.Length;
int x = 0;
Console.WriteLine("Count of pairs with given XOR = "
+ xorPairCount(arr, n, x));
}
}
// This code has been contributed by 29AjayKumar
Javascript
输出:
Count of pairs with given XOR = 1
时间复杂度: O(n)
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。