From 6b513d0c4169b671900b6b1a91ca95a6036699f5 Mon Sep 17 00:00:00 2001 From: Xu Shaohua Date: Wed, 22 May 2024 15:35:48 +0800 Subject: [PATCH] leetcode: Add 0260 --- .../0260.single-number-iii/Cargo.toml | 7 ++ src/leetcode/0260.single-number-iii/index.md | 4 ++ .../0260.single-number-iii/src/main.rs | 64 +++++++++++++++++++ 3 files changed, 75 insertions(+) create mode 100644 src/leetcode/0260.single-number-iii/Cargo.toml create mode 100644 src/leetcode/0260.single-number-iii/index.md create mode 100644 src/leetcode/0260.single-number-iii/src/main.rs diff --git a/src/leetcode/0260.single-number-iii/Cargo.toml b/src/leetcode/0260.single-number-iii/Cargo.toml new file mode 100644 index 000000000..90e53745c --- /dev/null +++ b/src/leetcode/0260.single-number-iii/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "lc-0260-single-number-iii" +version = "0.1.0" +edition = "2021" +publish = false + +[dependencies] diff --git a/src/leetcode/0260.single-number-iii/index.md b/src/leetcode/0260.single-number-iii/index.md new file mode 100644 index 000000000..77a618ba8 --- /dev/null +++ b/src/leetcode/0260.single-number-iii/index.md @@ -0,0 +1,4 @@ + +# + +[问题描述](../problems/) diff --git a/src/leetcode/0260.single-number-iii/src/main.rs b/src/leetcode/0260.single-number-iii/src/main.rs new file mode 100644 index 000000000..bb310a7e7 --- /dev/null +++ b/src/leetcode/0260.single-number-iii/src/main.rs @@ -0,0 +1,64 @@ +// Copyright (c) 2024 Xu Shaohua . All rights reserved. +// Use of this source is governed by General Public License that can be found +// in the LICENSE file. + +// bit-manipulation +// XOR +pub fn single_number1(nums: Vec) -> Vec { + // xor 是 a1 和 a2 共有的比特位 + let mut xor: i32 = 0; + for &num in &nums { + xor ^= num; + } + + let mut k: i32 = 1; + loop { + if (xor & k) != 0 { + break; + } + k *= 2; + } + + let mut a1: i32 = 0; + let mut a2: i32 = 0; + for &num in &nums { + if (num & k) == 0 { + a1 ^= num; + } else { + a2 ^= num; + } + } + + // 排序 + if a1 > a2 { + (a1, a2) = (a2, a1); + } + vec![a1, a2] +} + +pub type SolutionFn = fn(Vec) -> Vec; + +fn check_solution(func: SolutionFn) { + let nums = vec![1, 2, 1, 3, 2, 5]; + assert_eq!(func(nums), [3, 5]); + + let nums = vec![-1, 0]; + assert_eq!(func(nums), [-1, 0]); + + let nums = vec![0, 1]; + assert_eq!(func(nums), [0, 1]); +} + +fn main() { + check_solution(single_number1); +} + +#[cfg(test)] +mod tests { + use super::{check_solution, single_number1}; + + #[test] + fn test_single_number1() { + check_solution(single_number1); + } +}