arrays - 如何在随机排列的连续整数数组中找到重复元素?

标签 arrays algorithm duplicates

我最近在某处遇到一个问题:

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. Assume that you can access each element of the array only once. Describe an algorithm to find the repeated number. If you used auxiliary storage in your algorithm, can you find an algorithm that does not require it?

我想知道的是第二部分,即不使用辅助存储。你有什么想法吗?

最佳答案

只需将它们全部相加,然后减去如果仅使用 1001 个数字所期望的总数。

例如:

Input: 1,2,3,2,4 => 12
Expected: 1,2,3,4 => 10

Input - Expected => 2

关于arrays - 如何在随机排列的连续整数数组中找到重复元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2605766/

相关文章:

javascript - 在 JavaScript 中查找最长和最短的单词

python - 最接近零的两个产品之间的差异 : non brute-force solution?

mysql - 在 MySQL 中查找重复记录

Javascript:无法从循环内部修改在循环外部声明的数组

java - 将字符串附加到Java中的mongoDB文档中的现有数组

c# - 如何迭代不同长度的列表以找到所有排列?

在纯 C 的数组中选择具有更多重复项的元素

MySQL - 从两列中查找重复数据

将类型结构转换为固定大小数组的内存位置

vb.net - 在 vb.net 中查找列表值的所有组合(笛卡尔积)