Find a duplicate element in an array - 我的博客 - ITeye技术网站
Question:
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?
如果可以用辅助空间的话,可以用HashSet来处理,如果add失败说明有重复的。但是如果不能用额外空间的话呢?
Solution 1:
考虑加法。1+2+...+n = n(n-1)/2
假设数组所有元素之和为sum, 那么sum-n(n-1)/2就是我们要找的重复的数。
Read full article from Find a duplicate element in an array - 我的博客 - ITeye技术网站
No comments:
Post a Comment