Skip to content

Latest commit

 

History

History
30 lines (28 loc) · 762 Bytes

File metadata and controls

30 lines (28 loc) · 762 Bytes

🔮 Question

Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. Find all the elements that appear twice in this array. Could you do it without extra space and in O(n) runtime?
Example:
Input:
[4,3,2,7,8,2,3,1]

Output:
[2,3]

🐉 Solution

class Solution {
    public List<Integer> findDuplicates(int[] nums) {
        List <Integer> list=new ArrayList<Integer>();
        int j,i;
        for(i=0;i<nums.length;i++){
            for(j=i+1;j<nums.length;j++){
                if(nums[i]==nums[j]){
                    list.add(nums[i]);
                    break;
                }
            }
        }
        return list;
    }
}