Movatterモバイル変換


[0]ホーム

URL:


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

Commit661fe56

Browse files
refactor 442
1 parent7b0a2f9 commit661fe56

File tree

1 file changed

+25
-19
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+25
-19
lines changed

‎src/main/java/com/fishercoder/solutions/_442.java

Lines changed: 25 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66
importjava.util.Set;
77

88
/**
9+
* 442. Find All Duplicates in an Array
10+
*
911
* Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
1012
1113
Find all the elements that appear twice in this array.
@@ -21,31 +23,35 @@ Could you do it without extra space and in O(n) runtime?
2123
*/
2224
publicclass_442 {
2325

24-
//O(n) space
25-
//O(n) time
26-
publicList<Integer>findDuplicates_solution1(int[]nums) {
27-
Set<Integer>set =newHashSet();
28-
List<Integer>result =newArrayList();
29-
for (inti :nums) {
30-
if (!set.add(i)) {
31-
result.add(i);
26+
publicstaticclassSolution1 {
27+
//O(n) space
28+
//O(n) time
29+
publicList<Integer>findDuplicates(int[]nums) {
30+
Set<Integer>set =newHashSet();
31+
List<Integer>result =newArrayList();
32+
for (inti :nums) {
33+
if (!set.add(i)) {
34+
result.add(i);
35+
}
3236
}
37+
returnresult;
3338
}
34-
returnresult;
3539
}
3640

37-
//O(1) space
38-
//O(n) time
39-
publicList<Integer>findDuplicates_solution2(int[]nums) {
40-
List<Integer>result =newArrayList();
41-
for (inti =0;i <nums.length;i++) {
42-
intindex =Math.abs(nums[i]) -1;
43-
if (nums[index] <0) {
44-
result.add(Math.abs(index +1));
41+
publicstaticclassSolution2 {
42+
//O(1) space
43+
//O(n) time
44+
publicList<Integer>findDuplicates(int[]nums) {
45+
List<Integer>result =newArrayList();
46+
for (inti =0;i <nums.length;i++) {
47+
intindex =Math.abs(nums[i]) -1;
48+
if (nums[index] <0) {
49+
result.add(Math.abs(index +1));
50+
}
51+
nums[index] = -nums[index];
4552
}
46-
nums[index] = -nums[index];
53+
returnresult;
4754
}
48-
returnresult;
4955
}
5056

5157
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp