
在本文中,我们将讨论在给定的唯一数字数组中计算唯一三元组(x,y,z)的数量,其中它们的异或为0。因此,三元组应该是唯一的,其中所有三个元素都是唯一的,并且将计算所有三元组的组合,例如−
Input : arr[ ] = { 5, 6, 7, 1, 3 }
Output : 2
Explanation : triplets are { 5, 6, 3 } and { 6, 7, 1 } whose XOR is zero.
Input : arr[ ] = { 3, 6, 8, 1, 5, 4 , 12}
Output : 3
Explanation : Triplets are { 3, 6, 5 }, { 1, 5, 4 } and { 4, 8, 12 } whose XOR is zero.寻找解决方案的方法
我们知道相同值的异或运算结果总是零。因此,我们要寻找独特的三元组,可以采用一种乐观的方法,即找到数组中两个值的异或结果,并将结果存储起来,然后在数组中搜索等于该结果的值。此外,结果的值不应与任何一对值相等。请查看
艺帆网络工作室网站源码,是国庆后新一批新概念的网站源码,采用流行的Html5和JS组合流畅顺滑,界面清晰明朗,适合科技类企业和公司建站使用。如果你是想成为一家独特的设计公司,拥有独特的文化,追求品质,而非数量与规模。 这种坚持一直贯穿于项目运作之中,从品牌建立、形象推广设计到品牌形象管理。那可以考虑使用这款艺帆网络工作室网站源码。 这款源码中服务项目和团队程序需要在_template文件夹下的in
示例
#includeusing namespace std; int main () { int arr[] = { 3, 6, 8, 1, 5, 4, 12 }; int n = sizeof (arr) / sizeof (arr[0]); int result; // count variable to keep count of pairs. int count = 0; // creating a set to store unique numbers . unordered_set < int >values; // inserting values in set. for (int i = 0; i < n; i++) values.insert (arr[i]); // traverse for all pairs to calculate XOR. for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { // finding xor of i, j pair. int XR = arr[i] ^ arr[j]; // checking if XOR value of pair present in array // and value should not be in pairs. if (values.find (XR) != values.end () && XR != arr[i] && XR != arr[j]) count++; } } // storing result result = count / 3; cout << "Number of unique triplets : " << result; return 0; }
输出
Number of unique triplets : 3
上述代码的解释
- 创建一个unordered_set
values来存储给定数组中的唯一数字。 - 使用for()循环通过values.insert(arr[i])将值插入集合中。
- 使用两个嵌套循环遍历所有的数对,并计算它们的异或值。
- 然后,在数组中搜索异或值,并在值在数组中而不在数对中时增加计数。
- 将结果存储为count / 3,这样就可以计算出三个组合的三元组数,而我们需要的是唯一的三元组。
结论
本文讨论了如何找到具有异或值为0的三元组的数量;我们讨论了一种乐观的方法来找到唯一的三元组。我们还讨论了用C++解决这个问题的程序。然而,我们可以用其他编程语言如Java、C、Python等来编写这个程序。希望本文对您有所帮助。










