4
pub fn four_sum(nums: Vec<i32>, target: i32) -> Vec<Vec<i32>> {5
let mut combinations: Vec<Vec<i32>> = vec![];10
} // can't have multiple of 412
// Convert the Vec<i32> to Vec<i64> to handle large numbers.13
let mut nums: Vec<i64> = nums.into_iter().map(|x| x as i64).collect();14
let target = target as i64;16
nums.sort_unstable(); // sort to allow left/right crawling19
if nums[i] * 4 > target {20
break; // no more solutions can be found if left most index (i) cannot divide/4 evenly or less than target21
} // considering all numbers right of (i) are either equal or larger!23
// traverse duplicates24
if i > 0 && nums[i] == nums[i - 1] {28
for j in i + 1..len - 2 {29
if nums[j] * 3 > target - nums[i] {30
continue; // continue j loop if second left most index (j) cannot divide/3 evenly or less than target - i33
// traverse duplicates34
if j > i + 1 && nums[j] == nums[j - 1] {38
let (mut left, mut right) = (j + 1, len - 1);41
let cur_val = nums[i] + nums[j] + nums[left] + nums[right];42
match cur_val.cmp(&target) {44
// if equal, push solution45
combinations.push(vec![52
// pull left and right inwards56
// then traverse any duplicates57
while left < right && nums[left] == nums[left - 1] {60
while left < right && nums[right] == nums[right + 1] {64
Ordering::Less => left += 1, // if sum is less move left to find a larger sum65
Ordering::Greater => right -= 1, // if sum is greater move right to find a smaller sum