Java Solution | O(n) time and O(1) space


  • -1
    R

    Idea is to use minus sign and array index, to mark the elements visited.

       public List<Integer> findDuplicates(int[] nums) {
            List<Integer> res = new ArrayList<>();
            for(int i = 0 ; i < nums.length; i++) {
                int n = Math.abs(nums[i]);
                if(nums[n - 1] < 0)
                    res.add(n);
                else
                    nums[n - 1] = - nums[n - 1];
            }
            return res;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.