Skip to content

use fold for single_number Solution1 #8

Description

@ChrisLinn

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);
    }
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions