fn main() {
let arr = [1, 2, 4, 4, 5, 6];
let target = 9;
let mut left = 0;
let mut right = arr.len() - 1;
let mut found = false;
while left < right {
let sum = arr[left] + arr[right];
if sum == target {
found = true;
break;
} else if sum < target {
left += 1;
} else {
right -= 1;
}
}
println!("{}", found);
}The code uses two pointers starting at the beginning and end of the sorted array. It checks sums and moves pointers accordingly. The pair (4,5) sums to 9, so found becomes true and prints true.
fn main() {
let mut arr = vec![1, 1, 2, 2, 3, 4, 4, 5];
let mut i = 0;
for j in 1..arr.len() {
if arr[j] != arr[i] {
i += 1;
arr[i] = arr[j];
}
}
arr.truncate(i + 1);
println!("{:?}", arr);
}The two pointers i and j move through the vector. When a new unique element is found, it is placed at i+1. Finally, the vector is truncated to keep only unique elements.
fn main() {
let mut arr = vec![2, 8, 4, 12, 10, 6];
let mut left = 0;
let mut right = arr.len() - 1;
while left < right {
while left < right && arr[left] % 2 == 0 {
left += 1;
}
while left < right && arr[right] % 2 == 1 {
right -= 1;
}
if left < right {
arr.swap(left, right);
left += 1;
right -= 1;
}
}
println!("{:?}", arr);
}The inner while loops increment left and decrement right without checking if they go out of array bounds. This can cause left or right to exceed valid indices, leading to a runtime panic.
fn max_area(height: Vec<i32>) -> i32 {
let mut left = 0;
let mut right = height.len() - 1;
let mut max_area = 0;
while left < right {
let width = (right - left) as i32;
let min_height = if height[left] < height[right] { height[left] } else { height[right] };
let area = width * min_height;
if area > max_area {
max_area = area;
}
if height[left] < height[right] {
left += 1;
} else {
right -= 1;
}
}
max_area
}
fn main() {
let heights = vec![1,8,6,2,5,4,8,3,7];
println!("{}", max_area(heights));
}The two pointer approach calculates area between left and right pointers, moving the pointer with smaller height inward. The maximum area for the given input is 49.
The two pointer technique starts from both ends and moves inward, comparing characters. It stops immediately if a mismatch is found, making it efficient by avoiding unnecessary checks.
