-
Notifications
You must be signed in to change notification settings - Fork 0
/
Finding all duplicates in Array
53 lines (37 loc) · 1.49 KB
/
Finding all duplicates in Array
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
Given an integer array nums of length n where all the integers of nums are in the range [1, n] and each integer appears once or twice, return an array of all the integers that appears twice.
You must write an algorithm that runs in O(n) time and uses only constant extra space.
Example 1:
Input: nums = [4,3,2,7,8,2,3,1]
Output: [2,3]
Example 2:
Input: nums = [1,1,2]
Output: [1]
Example 3:
Input: nums = [1]
Output: []
Constraints:
n == nums.length
1 <= n <= 105
1 <= nums[i] <= n
Each element in nums appears once or twice.
solution:
interview preperation
we can sort array and finding two elements near by are equal then they are duplicates O(Nlogn)
by using hash map or frequency map(O(NlogN)
So we use by updating array we taking indexes and updating and checking whether it is updated before if it is updated before it is the duplicate element
Given an integer array nums of length n where all the integers of nums are in the range [1, n] and each integer appears once or twice, return an array of all the integers that appears twice.
You must write an algorithm that runs in O(n) time and uses only constant extra space.
https://www.youtube.com/watch?v=mWs3sIXPXwM
class Solution {
public List<Integer> findDuplicates(int[] nums) {
List<Integer> ans = new ArrayList<>();
for(int i=0;i<nums.length;i++){
int x = Math.abs(nums[i]);
if(nums[x-1] < 0){
ans.add(x);
}
nums[x-1] *=-1;
}
return ans;
}
}