aboutsummaryrefslogtreecommitdiff
path: root/set_mismatch.rs
blob: b490f8eca97512204f36cd4e42b147b924e354be (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
struct Solution;

impl Solution {
    pub fn find_error_nums(nums: Vec<i32>) -> Vec<i32> {
        let mut xor = nums.iter().zip(1..=nums.len() as i32).fold(0, |acc, (&num, i)| acc ^ num ^ i);
        xor &= -xor;
        let (mut n0, mut n1) = (0, 0);
        for &n in &nums {
            if n & xor == 0 {
                n0 ^= n;
            } else {
                n1 ^= n;
            }
        }
        for i in 1..=nums.len() as i32 {
            if i & xor == 0 {
                n0 ^= i;
            } else {
                n1 ^= i;
            }
        }
        for &n in &nums {
            if n == n0 {
                return vec![n0, n1];
            }
            if n == n1 {
                return vec![n1, n0];
            }
        }
        unreachable!()
    }
}

fn main() {
    let nums = vec![1,2,2,4];
    print!("{:?}", Solution::find_error_nums(nums));
}