Skip to content

Commit 4d348de

Browse files
committed
How to find a duplicate element in an array
1 parent 8a65c74 commit 4d348de

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
#!/usr/bin/env python
2+
3+
#Suppose you have an array of 1001 integers. The integers are in random order,
4+
# but you know each of the integers is between 1 and 1000 (inclusive).
5+
# In addition, each number appears only once in the array, except for
6+
# one number, which occurs twice. Assume that you can access each element
7+
# of the array only once. Describe an algorithm to find the repeated number.
8+
# If you used auxiliary storage in your algorithm, can you find an algorithm
9+
# that does not require it?
10+
11+
import random
12+
import sys
13+
14+
def GenArray(length):
15+
array = range(1,length + 1)
16+
dup = random.randint(1, length)
17+
print 'Dup num generated: %s' % dup
18+
array.append(dup)
19+
random.shuffle(array)
20+
return array
21+
22+
def XorFind(array):
23+
print 'Start Xor find ...'
24+
found = 0
25+
for i, item in enumerate(array):
26+
found = found ^ item ^ i
27+
# An alternative:
28+
#for i in xrange(1, length + 2):
29+
# found = found ^ array[i-1] ^ (i - 1)
30+
print 'Dup num founded (Xor): %s' % found
31+
32+
def SumFind(array):
33+
print 'Start Sum find ...'
34+
length = len(array)
35+
expect_sum = (1 + length - 1) * (length - 1) / 2
36+
real_sum = reduce(lambda x, y : x + y, array)
37+
print 'Dup num founded (Sum): %s' % (real_sum - expect_sum)
38+
39+
if __name__ == '__main__':
40+
length = int(sys.argv[1])
41+
array = GenArray(length)
42+
XorFind(array)
43+
SumFind(array)

0 commit comments

Comments
 (0)