Skip to content

use fold for single_number Solution1 #8

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
ChrisLinn opened this issue Jul 19, 2019 · 0 comments
Open

use fold for single_number Solution1 #8

ChrisLinn opened this issue Jul 19, 2019 · 0 comments

Comments

@ChrisLinn
Copy link
Collaborator

ChrisLinn commented Jul 19, 2019

https://github.com/rust-interview/rust-leetcode-solutions/blob/master/kamyu104/src/single_number_ii.rs#L12

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=35f73d98e6255726e489147a0e8206d5

// Time:  O(n)
// Space: O(1)

pub struct Solution {}

impl Solution {
    pub fn single_number(nums: Vec<i32>) -> i32 {
        let (one, _) = nums.iter().fold((0, 0), |(one, two), num| {
            (
                (!num & one) | (num & !one & !two),
                (!num & two) | (num & one),
            )
        });
        one
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_add() {
        assert_eq!(Solution::single_number(vec![2, 2, 3, 2]), 3);
        assert_eq!(Solution::single_number(vec![0, 1, 0, 1, 0, 1, 99]), 99);
        assert_eq!(Solution::single_number(vec![0, 0, 0, 1, 1, 1, 5]), 5);
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant