Skip to content

Commit a5d1359

Browse files
committed
'Single Number II' soln
1 parent 991f4b0 commit a5d1359

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

leetcode/single_number_ii.rs

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
///
2+
/// Problem: Single Number II
3+
///
4+
/// Given an integer array nums where every element appears three times except for one,
5+
/// which appears exactly once. Find the single element and return it.
6+
///
7+
/// You must implement a solution with a linear runtime complexity and use only constant
8+
/// extra space.
9+
///
10+
/// Example 1:
11+
/// Input: nums = [2,2,3,2]
12+
/// Output: 3
13+
///
14+
/// Example 2:
15+
/// Input: nums = [0,1,0,1,0,1,99]
16+
/// Output: 99
17+
///
18+
/// Constraints:
19+
/// 1 <= nums.length <= 3 * 10^4
20+
/// -2^31 <= nums[i] <= 2^31 - 1
21+
/// Each element in nums appears exactly three times except for one element which appears once.
22+
///
23+
24+
// # Solution
25+
// Time complexity: O(n)
26+
// Space complexity: O(1)
27+
28+
impl Solution {
29+
pub fn single_number(nums: Vec<i32>) -> i32 {
30+
let mut ones = 0;
31+
let mut twos = 0;
32+
33+
for num in nums {
34+
ones = (ones ^ num) & !twos;
35+
twos = (twos ^ num) & !ones;
36+
37+
}
38+
ones
39+
}
40+
}

0 commit comments

Comments
 (0)