19. Find All Duplicates in an Array
Topic :
arrays
Difficulty :
medium
Problem Link :
problem statement
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
import java.io.*;
import java.util.*;
class Find_All_Duplicates
{
public static void main (String args[])
{
int nums[]={4,3,2,7,8,2,3,1};
System.out.println(findDuplicates(nums));
}
static List<Integer> findDuplicates(int[] nums) {
List <Integer> ans= new ArrayList<>();
int i=0;
while(i<nums.length)
{
int correctIndex=nums[i]-1;
if(nums[correctIndex]!=nums[i])
{
int temp=nums[correctIndex];
nums[correctIndex]=nums[i];
nums[i]=temp;
}
else
{
i++;
}
}
for(int ind=0;ind<nums.length;ind++)
{
if(nums[ind]!=ind+1)
ans.add(nums[ind]);
}
return ans;
}
}