Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 366982f

Browse files
Create Find Duplicate in Array .java
1 parent 2f741cb commit 366982f

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

‎Array/Find Duplicate in Array .java

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/*
2+
Given a read only array of n + 1 integers between 1 and n, find one number that repeats in linear time using less than O(n) space and traversing the stream sequentially O(1) times.
3+
4+
Sample Input:
5+
6+
[3 4 1 4 1]
7+
Sample Output:
8+
9+
1
10+
If there are multiple possible answers ( like in the sample case above ), output any one.
11+
12+
If there is no duplicate, output -1
13+
*/
14+
15+
public class Solution {
16+
// DO NOT MODIFY THE LIST. IT IS READ ONLY
17+
public int repeatedNumber(final List<Integer> A) {
18+
int len = A.size();
19+
if(len == 0)
20+
return -1;
21+
int slow = A.get(0);
22+
int fast = A.get(A.get(0));
23+
while (slow != fast) {
24+
slow = A.get(slow);
25+
fast = A.get(A.get(fast));
26+
}
27+
28+
fast = 0;
29+
while (slow != fast) {
30+
slow = A.get(slow);
31+
fast = A.get(fast);
32+
}
33+
if(slow==0) return -1;
34+
return slow;
35+
}
36+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /