-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindTheDuplicateNumber.java
More file actions
52 lines (38 loc) · 909 Bytes
/
FindTheDuplicateNumber.java
File metadata and controls
52 lines (38 loc) · 909 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// Array approach
class Solution {
public int findDuplicate(int[] nums) {
int length = nums.length;
int[] data = new int[length];
for(int i=0;i<length;i++) {
data[nums[i]-1]++;
}
for(int i=0;i<length;i++) {
if (data[i]>1) return i+1;
}
return -1;
}
}
// Cyclic Sort Approach
class Solution {
public int findDuplicate(int[] nums) {
int i = 0;
while (i < nums.length) {
if (arr[i] != i+1) {
int correct = arr[i] - 1;
if (arr[i] != arr[correct]) {
swap(arr, i, correct);
} else {
return arr[i];
}
} else {
i++;
}
}
return -1;
}
static void swap(int[] arr, int first, int second) {
int temp = arr[first];
arr[first] = arr[second];
arr[second] = temp;
}
}