diff --git a/src/problem/mod.rs b/src/problem/mod.rs index cb4a126..d00e9a5 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -306,3 +306,5 @@ mod p3255_find_the_power_of_k_size_subarrays_ii; mod p3235_check_if_the_rectangle_corner_is_reachable; mod p3242_design_neighbor_sum_service; + +mod p540_single_element_in_a_sorted_array; diff --git a/src/problem/p540_single_element_in_a_sorted_array.rs b/src/problem/p540_single_element_in_a_sorted_array.rs new file mode 100644 index 0000000..b156d13 --- /dev/null +++ b/src/problem/p540_single_element_in_a_sorted_array.rs @@ -0,0 +1,43 @@ +/** + * [540] Single Element in a Sorted Array + */ +pub struct Solution {} + +// submission codes start here + +impl Solution { + pub fn single_non_duplicate(nums: Vec) -> i32 { + let n = nums.len(); + let (mut left, mut right) = (0, n - 1); + + while left < right { + let middle = (right - left) / 2 + left; + if nums[middle] == nums[middle ^ 1] { + left = middle + 1; + } else { + right = middle; + } + } + + nums[left] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_540() { + assert_eq!( + 2, + Solution::single_non_duplicate(vec![1, 1, 2, 3, 3, 4, 4, 8, 8]) + ); + assert_eq!( + 10, + Solution::single_non_duplicate(vec![3, 3, 7, 7, 10, 11, 11]) + ); + } +}