-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path217. Contain Dublicates
More file actions
40 lines (36 loc) · 974 Bytes
/
217. Contain Dublicates
File metadata and controls
40 lines (36 loc) · 974 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
// 2 loop tc O (n2)
class Solution {
public boolean containsDuplicate(int[] nums) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] == nums[j]) return true;
}
}
return false;
}
}
// Sorting Array TC O(n log n) SC - O(1)
import java.util.*;
class Solution {
public boolean containsDuplicate(int[] nums) {
Arrays.sort(nums);
for (int i = 1; i < nums.length; i++) {
if (nums[i] == nums[i - 1]) return true;
}
return false;
}
}
// hashSet tc -O(n) sc -O(n)
import java.util.*;
class Solution {
public boolean containsDuplicate(int[] nums) {
Set<Integer> seen = new HashSet<>();
for (int num : nums) {
if (seen.contains(num)) {
return true; // duplicate found
}
seen.add(num);
}
return false; // all unique
}
}