442. Find All Duplicates in an Array

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]

Rust Solution

struct Solution;

impl Solution {
    fn find_duplicates(mut nums: Vec<i32>) -> Vec<i32> {
        let mut res: Vec<i32> = vec![];
        let n = nums.len();
        for i in 0..n {
            let x = nums[i];
            let index = (x.abs() - 1) as usize;
            if nums[index] < 0 {
                res.push(x.abs());
            } else {
                nums[index] *= -1;
            }
        }
        res
    }
}

#[test]
fn test() {
    let nums = vec![4, 3, 2, 7, 8, 2, 3, 1];
    let res = vec![2, 3];
    assert_eq!(Solution::find_duplicates(nums), res);
}

Having problems with this solution? Click here to submit an issue on github.