Skip to content

Commit 31b8fcd

Browse files
committed
Solve the problem #442
1 parent 00f4890 commit 31b8fcd

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package org.sean.array;
2+
3+
import java.util.Arrays;
4+
import java.util.Collections;
5+
import java.util.LinkedList;
6+
import java.util.List;
7+
8+
/***
9+
* 442. Find All Duplicates in an Array
10+
*/
11+
public class DuplicatesFinder {
12+
public List<Integer> findDuplicates(int[] nums) {
13+
if (nums == null || nums.length <= 1)
14+
return Collections.emptyList();
15+
16+
int length = nums.length;
17+
18+
int mask = ~(1 << 31);
19+
List<Integer> result = new LinkedList<>();
20+
21+
for (int i = 0; i < length; i++) {
22+
int pos = (nums[i] & mask) - 1;
23+
24+
int flag = (nums[pos] >> 31) & 0x01;
25+
if (flag == 1) { // already marked
26+
result.add(nums[i] & mask);
27+
} else {
28+
nums[pos] = (1 << 31) | nums[pos];// mark the value
29+
}
30+
}
31+
return result;
32+
}
33+
34+
public static void main(String[] args) {
35+
int[] array = {4, 3, 2, 7, 8, 2, 3, 1};
36+
List<Integer> duplicates = new DuplicatesFinder().findDuplicates(array);
37+
System.out.println(Arrays.toString(duplicates.toArray()));
38+
}
39+
}

0 commit comments

Comments
 (0)