Crate closest_sum_pair[][src]

Expand description

closest_sum_pair

Finds two numbers in a Vec<i32>, that has the closest sum to a given number. If there are multiple choices, pair that has most distance between them is selected.

The algorithm has time complexity of O(NlogN) and space complexity of O(1).

Quick Start

use closest_sum_pair::Elements;

let mut list: Vec<i32> = vec![-2, -4, -7, -2, -5, -13, -7];

let len: usize = list.len();

let desired_sum: i32 = -1;

let mut elements = Elements::new(&mut list, len, desired_sum);

let pair: (i32, i32) = elements
    .sort_list()
    .find_init_distance()
    .find_pair()
    .result();

assert_eq!((-2, -2), pair);

Structs

This struct holds 5 pieces of information related to the list.

1.list: A mutable ref to a Vec<i32>.

2.len: Length of the vector.

3.desired_sum: This is a value that users will provide. This is the target value for the pairs.

4.pair: Pair that has the closest sum to desired_sum.

5.init_distance: Initialize the distance to number that is always greater than sum of any two numbers in list - desired sum.