在许多情况下,使用XOR运算符来查找数组中的重复元素失败 [英] Using XOR operator for finding duplicate elements in a array fails in many cases

查看:151
本文介绍了在许多情况下,使用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 ?

推荐答案

从原始问题:


假设你有一个1001整数的数组。整数是随机的,但你知道每个整数在1到1000(含)之间。此外,每个数字在数组中只显示一次,除了一个数字,出现两次。

Suppose you have an array of 1001 integers. The integers are in random order, but you know each of the integers is between 1 and 1000 (inclusive). In addition, each number appears only once in the array, except for one number, which occurs twice.

它基本上说,该算法只有当您有连续的整数以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运算符来查找数组中的重复元素失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆