-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day6_Duplicate.java
92 lines (72 loc) · 1.83 KB
/
Day6_Duplicate.java
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
//Sorting using one for loop
class Solution {
public List<Integer> findDuplicates(int[] nums) {
List<Integer> ans = new ArrayList<>();
for(int i=0;i<nums.length-1;i++)
{
if(nums[i]>nums[i+1])
{
int temp=nums[i];
nums[i]=nums[i+1];
nums[i+1]=temp;
i=-1;
}
}
System.out.println(Arrays.toString(nums));
for(int i=0;i<nums.length-1;i++)
{
if(nums[i]==nums[i+1])
ans.add(nums[i]);
}
return ans;
}
}
//iF only one number is repeated
class Solution {
public List<Integer> findDuplicates(int[] nums) {
List<Integer> ans = new ArrayList<>();
int slow=0,fast=0;
System.out.println(Arrays.toString(nums));
do{
slow=nums[slow];
fast=nums[nums[fast]];
}while(nums[slow]!=nums[fast]);
slow=0;
while(nums[slow]!=nums[fast])
{
slow=nums[slow];
fast=nums[fast];
ans.add(nums[slow]);
nums[slow]=0;
}
return ans;
}
}
//visited number is multiplied by -1 and while iterating if its negative the number is repeated
class Solution {
public List<Integer> findDuplicates(int[] nums) {
List<Integer> ans = new ArrayList<>();
for (int num : nums) {
if (nums[Math.abs(num) - 1] < 0) { // seen before
ans.add(Math.abs(num));
}
nums[Math.abs(num) - 1] *= -1;
}
return ans;
}
}
class Solution{
public List<Integer> findDuplicates(int[] nums)
{
List<Integer> ans= new ArrayList<>();
Set<Integer> visited = new HashSet<>();
for(int num:nums)
{
if(visited.contains(num))
ans.add(num);
else
visited.add(num);
}
return ans;
}
}