本文介绍了在许多情况下,使用XOR运算符来查找数组中的重复元素失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个帖子,但后来意识到这对许多输入失败。

I came across a post How to find a duplicate element in an array of shuffled consecutive integers? but later realized that this fails for many input.

例如:

arr [] = {601,602,603,604,605,605,606,607}

#include <stdio.h>
int main()
{
int arr[] = {2,3,4,5,5,7};
int i, dupe = 0;
for (i = 0; i < 6; i++) {
    dupe = dupe ^ a[i] ^ i;
}
printf ("%d\n", dupe);
return 0;
}

如何修改此代码,以便可以为所有人找到重复的元素案例?

How can I modify this code so that the duplicate element can be found for all the cases ?

推荐答案

从原始问题:

它基本上说,该算法只有当您有连续的整数以1 开头,以某些N结尾时才有效。

It basically says, that algorithm only works when you have consecutive integers, starting with 1, ending with some N.

如果要将其修改为更一般的情况,您必须执行以下操作:

If you want to modify it to more general case, you have to do following things:

在数组中查找最小和最大值。然后计算预期输出(x或最小和最大之间的所有整数)。然后计算数组中所有元素的xor。那么这两件事,你得到一个输出。

Find minimum and maximum in array. Then calculate expected output (xor all integers between minimum and maximum). Then calculate xor of all elements in array. Then xor this two things and you get an output.

这篇关于在许多情况下,使用XOR运算符来查找数组中的重复元素失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-16 15:16
查看更多