|
| 1 | +package com.Sorting_Problems._04_Cyclic_Sort_Problems; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.Arrays; |
| 5 | + |
| 6 | +/* |
| 7 | +Given an integer array nums of length n where all the integers of nums |
| 8 | +are in the range [1, n] and each integer appears once or twice, |
| 9 | +return an array of all the integers that appears twice. |
| 10 | +
|
| 11 | +You must write an algorithm that runs in O(n) time and uses only constant extra space. |
| 12 | +
|
| 13 | +Example 1: |
| 14 | +Input: nums = [4,3,2,7,8,2,3,1] |
| 15 | +Output: [2,3] |
| 16 | + */ |
| 17 | +public class _08_Find_all_Duplicates_in_Array { |
| 18 | + public static void main(String[] args) { |
| 19 | + int[] arr = {4,3,2,7,8,2,3,1}; |
| 20 | + System.out.println("Duplicate Elements: "+ findDuplicates(arr)); |
| 21 | + } |
| 22 | + static ArrayList<Integer> findDuplicates(int[] nums) { |
| 23 | + int i = 0; |
| 24 | + while(i < nums.length) { |
| 25 | + int correct = nums[i] - 1; |
| 26 | + if (nums[i] != nums[correct]) { |
| 27 | + swap(nums, i, correct); |
| 28 | + } else { |
| 29 | + i++; |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + // just find missing numbers |
| 34 | + ArrayList<Integer> ans = new ArrayList<>(); |
| 35 | + for (int index = 0; index < nums.length; index++) { |
| 36 | + if(nums[index] != index+1) { |
| 37 | + ans.add(nums[index]); |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + return ans; |
| 42 | + } |
| 43 | + static void swap(int[] arr, int first, int second) { |
| 44 | + int temp = arr[first]; |
| 45 | + arr[first] = arr[second]; |
| 46 | + arr[second] = temp; |
| 47 | + } |
| 48 | +} |
0 commit comments